MySQL Cursors – Beginner Tutorial
1. What is a Cursor?
A cursor allows us to process query results one row at a time.
Normally, a SELECT statement returns multiple rows together. A cursor lets us fetch and process each row individually.
2. Steps Involved in a Cursor
1. DECLARE: Define the SELECT query.
2. DECLARE HANDLER: Detect when no more rows exist.
3. OPEN: Execute the cursor query.
4. FETCH: Retrieve one row at a time.
5. LOOP: Repeat until all rows are processed.
6. CLOSE: Release the cursor.
3. Our Example Database
We will use the existing accounts table.
account_id | holder_name | balance
----------------------------------
1 | Asha | 5000.00
2 | Ravi | 3000.00
3 | Maya | 2500.00
4. Stored Procedure Using a Cursor
Let's create a procedure that fetches account holder names one by one and displays them.
DELIMITER //
CREATE PROCEDURE show_accounts()
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE acc_name VARCHAR(50);
-- 1. Declare cursor
DECLARE acc_cursor CURSOR FOR
SELECT holder_name FROM accounts;
-- 2. Declare handler
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET done = 1;
-- 3. Open cursor
OPEN acc_cursor;
-- 4. Fetch records
read_loop: LOOP
FETCH acc_cursor INTO acc_name;
IF done = 1 THEN
LEAVE read_loop;
END IF;
SELECT acc_name;
END LOOP;
-- 5. Close cursor
CLOSE acc_cursor;
END //
DELIMITER ;
5. Execute the Procedure
CALL show_accounts();
Expected values:
Asha
Ravi
Maya
6. Understanding the NOT FOUND Handler
What happens when FETCH tries to retrieve a row but no more rows are available?
MySQL raises a NOT FOUND condition.
We handle it using:
DECLARE CONTINUE HANDLER FOR NOT FOUND
SET done = 1;
This sets done = 1. The loop checks
this variable and exits when it becomes 1.
7. Practice Question
Create a stored procedure named show_account_balances().
Use a cursor to fetch the account_id
and balance of every account and
display them one by one.
Expected output:
1 | 5000.00
2 | 3000.00
3 | 2500.00
Hint: Declare two variables and use both in FETCH. The rest of the cursor structure remains almost identical to the previous example.