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.
Result:
| result |
|---|
| Laptop (899.00); Phone (599.00); Desk (249.00); |
The order of declarations matters: variables first, then cursors, then handlers.
Handlers
| Type | Behaviour |
|---|---|
CONTINUE HANDLER | Run the handler code, then continue after the statement that failed |
EXIT HANDLER | Run 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.
Result:
| result |
|---|
| a@x.com added |
Result:
| result |
|---|
| a@x.com already exists |
Reading the Error: GET DIAGNOSTICS
Result:
| state_code | error_no | error_text |
|---|---|---|
| 23000 | 1062 | Duplicate entry 'b@x.com' for key 'emails.PRIMARY' |
SIGNAL: Raise Your Own Errors
Use SQLSTATE '45000' for user-defined errors:
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:
Result:
| scheduler_state |
|---|
| ON |
It is ON by default in MySQL 8. Create a recurring clean-up:
Here is a short event that really runs, to prove it works. It inserts a row one second from now and removes itself:
Result:
| waited |
|---|
| 0 |
Result:
| rows_inserted_by_event |
|---|
| 1 |
Result:
| event_still_exists |
|---|
| 0 |
Common Beginner Mistakes
| Mistake | What happens | Fix |
|---|---|---|
Cursor for something a single UPDATE can do | Very slow | Use set-based SQL |
| Declaring handler before cursor | Error 1337 | Variables, cursors, then handlers |
Forgetting the NOT FOUND handler | Error 1329 at the end of data | Declare it |
| Event scheduler off | Events never run | Check @@event_scheduler |
| Swallowing errors with a silent handler | Bugs go unnoticed | Log or RESIGNAL |
Practice
- Write a cursor that totals each customer's spend into a table.
- Rewrite it as one
INSERT ... SELECTand compare. - Add an
EXIT HANDLERfor duplicate keys. - 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.

