MySQL Cursors, Handlers, SIGNAL and the Event Scheduler

MySQL 60 min min read Updated: Nov 27, 2026 Advanced
MySQL Cursors, Handlers, SIGNAL and the Event Scheduler
Advanced Topic 3 of 3

Cursors: One Row at a Time

SQL normally works on sets of rows. A cursor lets a stored program walk through a result one row at a time. Use it only when set-based SQL cannot do the job, because cursors are slow.

The pattern: DECLARE the cursor and a NOT FOUND handler, OPEN, FETCH in a loop, CLOSE.

sql CREATE PROCEDURE list_big_products(IN min_price DECIMAL(10,2)) BEGIN DECLARE done INT DEFAULT 0; DECLARE pname VARCHAR(100); DECLARE pprice DECIMAL(10,2); DECLARE collected TEXT DEFAULT ''; DECLARE cur CURSOR FOR SELECT name, price FROM products WHERE price >= min_price ORDER BY price DESC; DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; OPEN cur; read_loop: LOOP FETCH cur INTO pname, pprice; IF done = 1 THEN LEAVE read_loop; END IF; SET collected = CONCAT(collected, pname, ' (', pprice, '); '); END LOOP; CLOSE cur; SELECT collected AS result; END; CALL list_big_products(200);

Result:

result
Laptop (899.00); Phone (599.00); Desk (249.00);

The order of declarations matters: variables first, then cursors, then handlers.

Handlers

TypeBehaviour
CONTINUE HANDLERRun the handler code, then continue after the statement that failed
EXIT HANDLERRun the handler code, then leave the current BEGIN ... END block

Conditions to catch: SQLEXCEPTION (any error), SQLWARNING, NOT FOUND, a specific SQLSTATE '23000', or an error number such as 1062.

sql CREATE TABLE emails (email VARCHAR(30) PRIMARY KEY); CREATE PROCEDURE add_email(IN e VARCHAR(30)) BEGIN DECLARE EXIT HANDLER FOR 1062 SELECT CONCAT(e, ' already exists') AS result; INSERT INTO emails VALUES (e); SELECT CONCAT(e, ' added') AS result; END; CALL add_email('a@x.com'); CALL add_email('a@x.com');

Result:

result
a@x.com added

Result:

result
a@x.com already exists

Reading the Error: GET DIAGNOSTICS

sql CREATE TABLE emails (email VARCHAR(30) PRIMARY KEY); CREATE PROCEDURE add_email2(IN e VARCHAR(30)) BEGIN DECLARE code VARCHAR(5); DECLARE msg TEXT; DECLARE num INT; DECLARE EXIT HANDLER FOR SQLEXCEPTION BEGIN GET DIAGNOSTICS CONDITION 1 code = RETURNED_SQLSTATE, num = MYSQL_ERRNO, msg = MESSAGE_TEXT; SELECT code AS state_code, num AS error_no, msg AS error_text; END; INSERT INTO emails VALUES (e); END; CALL add_email2('b@x.com'); CALL add_email2('b@x.com');

Result:

state_codeerror_noerror_text
230001062Duplicate entry 'b@x.com' for key 'emails.PRIMARY'

SIGNAL: Raise Your Own Errors

Use SQLSTATE '45000' for user-defined errors:

sql CREATE PROCEDURE withdraw(IN bal DECIMAL(10,2), IN amt DECIMAL(10,2)) BEGIN IF amt > bal THEN SIGNAL SQLSTATE '45000' SET MESSAGE_TEXT = 'Insufficient funds', MYSQL_ERRNO = 1644; END IF; SELECT bal - amt AS new_balance; END; CALL withdraw(100, 150);
Error

ERROR 1644: Insufficient funds

RESIGNAL inside a handler passes the error on to the caller after your cleanup.

The Event Scheduler

An event is a job MySQL runs on a schedule, like a cron job inside the database. The scheduler thread must be on:

sql SELECT @@event_scheduler AS scheduler_state;

Result:

scheduler_state
ON

It is ON by default in MySQL 8. Create a recurring clean-up:

sql CREATE EVENT purge_old_sessions ON SCHEDULE EVERY 1 DAY STARTS '2025-01-01 02:00:00' DO DELETE FROM sessions WHERE last_seen < NOW() - INTERVAL 30 DAY; SHOW EVENTS; ALTER EVENT purge_old_sessions DISABLE; DROP EVENT purge_old_sessions;

Here is a short event that really runs, to prove it works. It inserts a row one second from now and removes itself:

sql CREATE TABLE ticks (n INT); CREATE EVENT one_shot ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 SECOND ON COMPLETION NOT PRESERVE DO INSERT INTO ticks VALUES (1); SELECT SLEEP(2) AS waited; SELECT COUNT(*) AS rows_inserted_by_event FROM ticks; SELECT COUNT(*) AS event_still_exists FROM information_schema.EVENTS WHERE EVENT_SCHEMA = DATABASE();

Result:

waited
0

Result:

rows_inserted_by_event
1

Result:

event_still_exists
0
Check the scheduler in production Managed services such as RDS keep the scheduler on, but a replica does not run events unless they are enabled there. Events run with the privileges of their definer.

Common Beginner Mistakes

MistakeWhat happensFix
Cursor for something a single UPDATE can doVery slowUse set-based SQL
Declaring handler before cursorError 1337Variables, cursors, then handlers
Forgetting the NOT FOUND handlerError 1329 at the end of dataDeclare it
Event scheduler offEvents never runCheck @@event_scheduler
Swallowing errors with a silent handlerBugs go unnoticedLog or RESIGNAL

Practice

  1. Write a cursor that totals each customer's spend into a table.
  2. Rewrite it as one INSERT ... SELECT and compare.
  3. Add an EXIT HANDLER for duplicate keys.
  4. Create an event that deletes cancelled orders older than a year.

Conclusion

Cursors walk rows one by one, handlers catch errors or end-of-data, SIGNAL raises custom errors, and events run scheduled SQL inside MySQL.

Quick Summary: cursor, CONTINUE HANDLER, EXIT HANDLER, GET DIAGNOSTICS, SIGNAL, EVENT.

Get Newsletter

Subscibe to our newsletter and we will notify you about the newest updates on Edugators