Cursors in MySQL allow you to iterate through a result set row by row. They are mainly used in stored procedures for processing query results sequentially when set-based operations are not suitable.
CONTINUE HANDLER FOR NOT FOUND to detect the end of the result set.
// Cursor declaration and usage outline
DECLARE cursor_name CURSOR FOR select_statement;
OPEN cursor_name;
FETCH cursor_name INTO variable_list;
CLOSE cursor_name;
-- Example stored procedure to process customers using a cursor
DELIMITER $$
CREATE PROCEDURE process_customers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE c_name VARCHAR(100);
DECLARE c_email VARCHAR(100);
DECLARE customer_cursor CURSOR FOR
SELECT name, email FROM customers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN customer_cursor;
read_loop: LOOP
FETCH customer_cursor INTO c_name, c_email;
IF done THEN
LEAVE read_loop;
END IF;
-- process each row: here we select a formatted string
SELECT CONCAT('Customer: ', c_name, ', Email: ', c_email);
END LOOP;
CLOSE customer_cursor;
END$$
DELIMITER ;
When process_customers() is executed, MySQL opens the cursor for the SELECT name, email FROM customers query and iterates row-by-row. For each row it fetches the values into c_name and c_email, then runs the SELECT that outputs a formatted string. The loop exits when the NOT FOUND handler sets done = TRUE.
Click buttons to control the cursor manually.
| name | |
|---|---|
| Alice Doe | alice@test.com |
| Bob Smith | bob@test.com |
| Charlie | charlie@test.com |
employees table and print each employee's details.