DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

Last call! Secure your stack and shape the future! Help dev teams across the globe navigate their software supply chain security challenges.

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Releasing software shouldn't be stressful or risky. Learn how to leverage progressive delivery techniques to ensure safer deployments.

Avoid machine learning mistakes and boost model performance! Discover key ML patterns, anti-patterns, data strategies, and more.

Related

  • Recover Distributed Transactions in MySQL
  • Enhancing Database Efficiency With MySQL Views: A Comprehensive Guide and Examples
  • Seamless Transition: Strategies for Migrating From MySQL to SQL Server With Minimal Downtime
  • How To Convert MySQL Database to SQL Server

Trending

  • Designing a Java Connector for Software Integrations
  • Beyond Code Coverage: A Risk-Driven Revolution in Software Testing With Machine Learning
  • How Trustworthy Is Big Data?
  • How To Develop a Truly Performant Mobile Application in 2025: A Case for Android
  1. DZone
  2. Coding
  3. Languages
  4. Using Cursors and Loops in MySQL

Using Cursors and Loops in MySQL

If you've ever wanted to learn how to write a MySQL cursor or a MySQL loop, you've come to the right place. Let's iterate!

By 
Oluwatomisin Bamimore user avatar
Oluwatomisin Bamimore
·
Everett Berry user avatar
Everett Berry
·
Nov. 19, 21 · Tutorial
Likes (1)
Comment
Save
Tweet
Share
8.7K Views

Join the DZone community and get the full member experience.

Join For Free
Dolphins image.

If you've ever wanted to learn how to write a MySQL cursor or a MySQL loop, you've come to the right place. Let's iterate!

Consider loops in general programming. They help you execute a specific sequence of instructions repeatedly until a particular condition breaks the loop. MySQL also provides a way to execute instructions on individual rows using cursors. Cursors in MySQL will execute a set of instructions on rows returned from SQL queries.

Properties of MySQL Cursors

  • Non-Scrollable: You can only iterate through rows in one direction. You can't skip a row; you can't jump to a row; you can't go back to a row.
  • Read-only: You can't update or delete rows using cursors.
  • Asensitive: MySQL cursors point to the underlying data. It runs faster than an insensitive cursor. Insensitive cursors point to a snapshot of the underlying data, making it slower than the asenstive cursors.

Creating a MySQL Cursor

To create a MySQL cursor, you'll need to work with the DECLARE, OPEN, FETCH, and CLOSE statements.

The Declare Statement

The DECLARE statement can declare variables, cursors, and handlers. There is a sequence of declarations that needs to be adhered to:

  • Variables
  • Cursors
  • Handlers

You must first declare at least one variable to use later with the FETCH statement later on.

DECLARE <variable_name>  <variable_type>


When declaring the cursor(s), you must attach a SELECT statement. Any valid SELECT statement will work. You also must declare at least one cursor.

DECLARE <cursor_name> CURSOR FOR <select_statement>


You also have to declare a NOT FOUND handler. When the cursor iterates and reaches the last row, it raises a condition that will be handled with the NOT FOUND handler. You can also declare other handlers depending on your needs. For example:

DECLARE CONTINUE HANDLER FOR NOT FOUND SET finished = 1;


The Open Statement

The OPEN statement initializes the result from the DECLARE cursor statement.

OPEN <cursor_name>


The Fetch Statement

The FETCH statement works as an iterator. It fetches the next row from the rows associated with the SELECT statement in the cursor declaration.

FETCH <cursor_name> INTO <variable_list>


The <variable_list> is one or more variables from the variables declared earlier.

FETCH <cursor_name> INTO a, b, c


If the next row exists, the variables store it; otherwise, a No Data condition with SQLSTATE of '02000' occurs. You can use the NOT FOUND handler to deal with this SQLSTATE.

The Close Statement

This statement closes the cursor opened in the `OPEN` statement.

CLOSE <cursor_name>


Using MySQL Cursors

Ready to start using MySQL cursors? First, you need to create a database and a table. In this demo, we will populate a table with data from this CSV file.

We will create a cursor that does the following:

  • Loops through the football table.
  • Calculates the average goals a home team that won a match scored at halftime.

Here's what the MySQL procedure should look like to accomplish this.

MySQL Procedure

DELIMITER $$ CREATE PROCEDURE cursordemo(INOUT average_goals FLOAT)
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE matches int DEFAULT(0);
DECLARE goals int DEFAULT(0);
DECLARE half_time_goals INT;
DECLARE team_cursor CURSOR FOR
SELECT
    HTHG
FROM
    epl.football
WHERE
    (FTR = "H");
    
DECLARE
    CONTINUE HANDLER FOR NOT FOUND
SET
    done = TRUE;

OPEN team_cursor;
teams_loop:
LOOP
    FETCH team_cursor INTO half_time_goals;
IF done THEN LEAVE teams_loop;
END IF;
SET
    goals = goals + half_time_goals;
SET
    matches = matches + 1;
END
LOOP
    teams_loop;
SET
    average_goals = goals / matches;
CLOSE team_cursor;

END $$ DELIMITER;


A procedure in MySQL is like a container that holds a sequence of instructions. Procedures are written in MySQL and stored in the database. We are defining the cursor inside a procedure because procedures are reusable. Executing the SQL procedure above will store the procedure in the database. We can call the procedure using its name, as shown below:

SET @average_goals = 0.0; 
CALL cursordemo(@average_goals); 
SELECT @average_goals;


The output of this operation is:

1.080954670906067



Screenshot.


Caveats of MySQL Cursors

A good look at the example shows that a SQL query like SELECT AVG(HTHG) FROM epl.football WHERE (FTR="H"); will achieve the same result. It would be best if you only used cursors when dealing with one row at a time. Examples are integrity checks, index rebuilds. Note that each time a cursor fetches a row, it results in round network trips. So, it may end up slowing down your MySQL server depending on how large the operation is.

Conclusion

In this article, we have seen how to use MySQL cursors and for loops, which function like iterative loops in general programming. We also covered variables, cursor, and handler declaration.

Using cursors can be computationally expensive. It would be best to use only them when MySQL does not provide any other way to achieve the same result using standard queries or user-defined functions. But, if that's the case, they are very powerful tools.

MySQL Database sql

Published at DZone with permission of Oluwatomisin Bamimore. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Recover Distributed Transactions in MySQL
  • Enhancing Database Efficiency With MySQL Views: A Comprehensive Guide and Examples
  • Seamless Transition: Strategies for Migrating From MySQL to SQL Server With Minimal Downtime
  • How To Convert MySQL Database to SQL Server

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!