๐ŸŽฏ MySQL Cursors โ€“ Row-by-Row Processing in Stored Procedures


๐Ÿงฒ Introduction โ€“ Why Use Cursors in MySQL?

A cursor in MySQL allows you to iterate through a result set row-by-row, enabling procedural operations that require loop-based processing inside stored procedures. While SQL is inherently set-based, cursors are useful when:

  • ๐Ÿ” You need to process each row with custom logic
  • ๐Ÿ› ๏ธ Performing operations not expressible via simple joins or updates
  • ๐Ÿš€ Automating tasks like batch updates or audits in procedural workflows

๐ŸŽฏ In this guide, youโ€™ll learn:

  • What cursors are and when to use them
  • How to declare, open, fetch, and close cursors
  • Cursor usage inside stored procedures
  • Best practices and performance notes

๐Ÿงฑ 1. What Is a Cursor in MySQL?

A cursor is a database object used to loop through a query result set one row at a time, usually within a LOOP, WHILE, or REPEAT block in a stored procedure.


๐Ÿ”ง 2. Cursor Lifecycle โ€“ Step-by-Step

StepCommandPurpose
DeclareDECLARE cursor_name CURSOR FOR ...Defines the query for the cursor
OpenOPEN cursor_name;Executes the query and prepares result set
FetchFETCH cursor_name INTO ...;Retrieves the next row from the result set
CloseCLOSE cursor_name;Releases memory and cursor object

๐Ÿ“ 3. Syntax โ€“ Declaring and Using Cursors

๐Ÿ”น Full Example

DELIMITER //

CREATE PROCEDURE process_employees()
BEGIN
  DECLARE done INT DEFAULT FALSE;
  DECLARE emp_id INT;
  DECLARE emp_name VARCHAR(100);

  -- Declare cursor
  DECLARE emp_cursor CURSOR FOR
    SELECT id, name FROM employees;

  -- Declare handler to detect end of result set
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

  -- Open cursor
  OPEN emp_cursor;

  -- Loop through rows
  read_loop: LOOP
    FETCH emp_cursor INTO emp_id, emp_name;
    IF done THEN
      LEAVE read_loop;
    END IF;

    -- Do something with each row
    INSERT INTO employee_logs(emp_id, action_time)
    VALUES (emp_id, NOW());
  END LOOP;

  -- Close cursor
  CLOSE emp_cursor;
END //

DELIMITER ;

๐Ÿ” 4. Explanation

  • DECLARE ... CURSOR FOR defines the query the cursor will use
  • OPEN starts the cursor
  • FETCH moves through the result set one row at a time
  • CONTINUE HANDLER FOR NOT FOUND ensures the loop ends when all rows are fetched
  • CLOSE frees memory and finalizes the cursor

๐Ÿง  Cursor Use Cases

Use CaseWhy Cursors Help
Row-level auditingLog changes for each row in a loop
Batch processing with conditionsApply logic to each record individually
Complex per-row calculationsRun nested queries or procedures per row
Cross-table lookupsProcess row-by-row updates with foreign logic

๐Ÿšซ When NOT to Use Cursors

๐Ÿšซ Donโ€™t Use Cursors ForUse This Instead
Simple row updatesUPDATE ... WHERE ...
AggregationsGROUP BY, SUM(), etc.
Multi-table joinsJOIN, MERGE

โœ… Cursors are slower than set-based queriesโ€”use only when necessary.


๐Ÿ“˜ Best Practices

โœ… Tip๐Ÿ’ก Why It Matters
Always close cursorsPrevent memory leaks or open sessions
Use cursors only inside stored proceduresMySQL does not support cursors outside procedures
Use handlers to manage end-of-cursorEnsures graceful loop exits
Keep cursor logic minimal and performantAvoid expensive logic inside loop
Test result set before using cursorsPrevents loops over large or unnecessary results

๐Ÿš€ Real-World Use Cases

ScenarioCursor Purpose
Archive inactive usersLoop through old users and insert into archive
Generate custom audit trailRecord changes row-by-row for reporting
Sync stock levels with vendor feedRow-wise comparison and update logic
Send alerts for flagged transactionsQuery alerts table and trigger messages per row

๐Ÿ“Œ Summary โ€“ Recap & Next Steps

Cursors in MySQL are a powerful tool when you need precise control over row-by-row operations within stored procedures. Use them wisely when set-based logic doesnโ€™t fit.

๐Ÿ” Key Takeaways

  • Cursors let you process results row-by-row in procedures
  • Require declaring, opening, fetching, and closing
  • Use CONTINUE HANDLER to detect end-of-data
  • Keep logic simple and efficient
  • Avoid cursors where SQLโ€™s set-based logic can do the job

โš™๏ธ Real-World Relevance

Used in data warehousing, financial systems, sync engines, and automated reporting where row-by-row analysis is necessary.


โ“ FAQ โ€“ MySQL Cursors


โ“ Can I use cursors outside of stored procedures?

โŒ No. Cursors are only valid inside stored programs (procedures/functions).


โ“ How do I exit a cursor loop?

Use a LEAVE statement with an IF done THEN ... check using a handler:

DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;

โ“ Can I fetch into multiple variables?

โœ… Yes. Just match the number of columns:

FETCH cursor_name INTO var1, var2, var3;

โ“ Can I nest cursors?

โœ… Yes, but it’s complex. Use with extreme care to avoid resource issues.


โ“ Do cursors improve performance?

โŒ Usually not. They are slower than set-based SQL. Use only when needed.


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐ŸŽฏ MySQL Cursors

Or Copy Link

CONTENTS
Scroll to Top