0
0
MySQLquery~5 mins

Cursors for row iteration in MySQL - Time & Space Complexity

Choose your learning style9 modes available
Time Complexity: Cursors for row iteration
O(n)
Understanding Time 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?

Scenario Under Consideration

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.

Identify Repeating Operations

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.
How Execution Grows With Input

As the number of rows grows, the number of fetch and process steps grows the same way.

Input Size (n)Approx. Operations
10About 10 fetch and process steps
100About 100 fetch and process steps
1000About 1000 fetch and process steps

Pattern observation: The work grows directly in proportion to the number of rows.

Final Time Complexity

Time Complexity: O(n)

This means the time to complete grows linearly with the number of rows processed.

Common Mistake

[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.

Interview Connect

Understanding how cursors work and their time cost helps you explain row-by-row processing clearly and shows you know how database operations scale.

Self-Check

What if we replaced the cursor with a single query that processes all rows at once? How would the time complexity change?