Cursors for row iteration in MySQL - Time & Space Complexity
When using cursors in MySQL, we want to understand how the time to process rows grows as the number of rows increases.
We ask: How does the work change when we have more rows to go through one by one?
Analyze the time complexity of the following cursor usage in MySQL.
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT id FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @emp_id;
IF done THEN
LEAVE read_loop;
END IF;
-- Process each employee id here
END LOOP;
CLOSE cur;
This code opens a cursor to go through each employee's id one by one and processes them.
Look for repeated steps in the code.
- Primary operation: Fetching each row from the cursor and processing it.
- How many times: Once for every row in the employees table.
As the number of rows grows, the number of fetch and process steps grows the same way.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 fetch and process steps |
| 100 | About 100 fetch and process steps |
| 1000 | About 1000 fetch and process steps |
Pattern observation: The work grows directly in proportion to the number of rows.
Time Complexity: O(n)
This means the time to complete grows linearly with the number of rows processed.
[X] Wrong: "Using a cursor is like running one query, so it always takes the same time regardless of rows."
[OK] Correct: Each row is fetched and processed one at a time, so more rows mean more steps and more time.
Understanding how cursors work and their time cost helps you explain row-by-row processing clearly and shows you know how database operations scale.
What if we replaced the cursor with a single query that processes all rows at once? How would the time complexity change?