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?
Practice
Solution
Step 1: Understand cursor functionality
Cursors allow you to handle each row of a query result individually instead of all at once.Step 2: Identify the correct purpose
Processing rows one by one matches the cursor's main use, unlike speeding inserts or creating tables.Final Answer:
To process query results row by row -> Option CQuick Check:
Cursor = row-by-row processing [OK]
- Thinking cursors speed up inserts
- Confusing cursors with backup tools
- Assuming cursors create tables
Solution
Step 1: Recall cursor lifecycle
First, you declare the cursor, then open it to start fetching rows, and finally close it when done.Step 2: Match the correct sequence
Only DECLARE, OPEN, FETCH, CLOSE follows the correct order of cursor operations.Final Answer:
DECLARE, OPEN, FETCH, CLOSE -> Option BQuick Check:
Cursor order = DECLARE -> OPEN -> FETCH -> CLOSE [OK]
- Opening cursor before declaring
- Fetching before opening
- Closing before fetching all rows
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT id FROM users;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @user_id;
IF done THEN
LEAVE read_loop;
END IF;
SELECT @user_id;
END LOOP;
CLOSE cur;What will this code output?
Solution
Step 1: Analyze cursor fetching loop
The cursor fetches each id from users table into @user_id, then prints it until no rows remain.Step 2: Understand handler and loop exit
The handler sets done = TRUE when no more rows, causing loop to exit properly after printing all ids.Final Answer:
It prints each user id from the users table one by one -> Option AQuick Check:
Cursor loop prints all rows one by one [OK]
- Assuming only first row prints
- Missing handler causes infinite loop
- Confusing session variables with local variables
DECLARE done INT DEFAULT FALSE;
DECLARE cur CURSOR FOR SELECT name FROM employees;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @emp_name;
IF done THEN
LEAVE read_loop;
END IF;
SELECT @emp_name;
END LOOP;
CLOSE cur;What is the likely cause of the infinite loop?
Solution
Step 1: Check for handler presence
The code lacks a CONTINUE HANDLER to set done = TRUE when no more rows are fetched.Step 2: Understand loop exit condition
Without setting done = TRUE, the IF condition never triggers LEAVE, causing infinite loop.Final Answer:
Missing CONTINUE HANDLER to set done = TRUE when no rows left -> Option DQuick Check:
No handler = infinite loop [OK]
- Forgetting CONTINUE HANDLER
- Assuming loop exits automatically
- Misplacing variable declarations
DECLARE done INT DEFAULT FALSE;
DECLARE total_salary DECIMAL(10,2) DEFAULT 0;
DECLARE cur CURSOR FOR SELECT salary FROM employees;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO @sal;
IF done THEN
LEAVE read_loop;
END IF;
SET total_salary = total_salary + @sal;
END LOOP;
CLOSE cur;
SELECT total_salary;What is the expected output of this procedure?
Solution
Step 1: Verify declaration order and variables
All local variables (done, total_salary) are declared before the cursor and handler. FETCH INTO @sal uses a session variable, which is valid.Step 2: Trace execution
The loop fetches each salary, adds it to total_salary until the handler sets done=TRUE, then SELECT outputs the sum.Final Answer:
The sum of all employee salaries -> Option AQuick Check:
Cursor loop + handler + accumulation = total sum [OK]
- Declaring variables after cursors/handlers
- Thinking @vars require DECLARE
- Missing handler or wrong loop condition
Ready to prove it?
Pass the test and this pattern moves unknown
