Iterate over rows in a stored procedure?
Assesses fundamental understanding of SQL & Databases conventions, runtime behavior, and memory/performance considerations.
Hiring managers look for precision, avoidance of ambiguous jargon, and ability to explain trade-offs under real production conditions.
To iterate row-by-row over a query result set inside a stored procedure, use a CURSOR:
### Cursor Lifecycle Steps:
DECLARE: Define the cursor and query.OPEN: Initialize the cursor result set.FETCH: Retrieve the next row into local variables.CLOSE: Free cursor memory resources.
DELIMITER //
CREATE PROCEDURE ProcessCustomers()
BEGIN
DECLARE done INT DEFAULT FALSE;
DECLARE cust_id INT;
DECLARE cur CURSOR FOR SELECT id FROM Customers;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = TRUE;
OPEN cur;
read_loop: LOOP
FETCH cur INTO cust_id;
IF done THEN
LEAVE read_loop;
END IF;
-- Process each customer ID here
END LOOP;
CLOSE cur;
END //
DELIMITER ;
*Performance Warning:* Databases are optimized for set-based operations. Cursors execute row-by-row ($O(n)$ procedural execution) and should only be used when set-based SQL logic is impossible.
Candidate Response Strategy & Interview Tips
- Start with a concise one-sentence summary: Deliver a direct, confident answer first before expanding into nuances.
- Demonstrate real-world trade-offs: Discuss where this approach excels and when you would avoid it in production systems.
- Discuss complexity & edge cases: Proactively explain time/space complexity or boundary conditions (null values, scale limits).
- Prepare for interviewer follow-ups: Technical hiring panels frequently probe deeper into concurrency, backward compatibility, or alternative libraries.