What if you could let the database handle each row for you, so you never miss a detail or make a mistake?
Why CURSOR concept and usage in SQL? - Purpose & Use Cases
Imagine you have a huge list of customer orders in a spreadsheet. You want to check each order one by one to apply a special discount if it meets certain conditions. Doing this manually means opening each row, reading the data, and updating it by hand.
Manually checking and updating each order is slow and tiring. It's easy to make mistakes, like skipping rows or applying the wrong discount. If the list is very long, it becomes almost impossible to keep track and stay accurate.
A CURSOR in SQL acts like a smart pointer that lets the computer go through each row of data one at a time. It automates the process of reading, checking, and updating rows without missing any. This way, you can handle complex row-by-row tasks safely and efficiently.
Open spreadsheet
For each row:
Check order
Apply discount if needed
Save changesDECLARE cursor CURSOR FOR SELECT * FROM orders; OPEN cursor; FETCH NEXT FROM cursor INTO variables; WHILE @@FETCH_STATUS = 0 BEGIN -- Check and update order; FETCH NEXT FROM cursor INTO variables; END CLOSE cursor; DEALLOCATE cursor;
CURSOR lets you process and update data row by row inside the database, making complex tasks simple and reliable.
A business wants to give a special bonus to customers who placed orders over $1000 last month. Using a CURSOR, the system can check each order, calculate the bonus, and update the customer records automatically.
Manual row-by-row data handling is slow and error-prone.
CURSOR automates processing each row safely inside the database.
This makes complex updates and checks easy and reliable.
Practice
CURSOR in SQL?Solution
Step 1: Understand what a cursor does
A cursor allows you to handle each row returned by a query individually, instead of all at once.Step 2: Compare options to cursor purpose
Options B, C, and D describe tasks unrelated to row-by-row processing, which is the cursor's main use.Final Answer:
To process query results row by row -> Option AQuick Check:
Cursor = row-by-row processing [OK]
- Thinking cursor speeds up bulk inserts
- Confusing cursor with table creation
- Assuming cursor automates backups
Solution
Step 1: Recall the cursor lifecycle
You first DECLARE the cursor, then OPEN it to start fetching rows, FETCH rows one by one, CLOSE it when done, and finally DEALLOCATE to free resources.Step 2: Match the correct sequence
Only DECLARE, OPEN, FETCH, CLOSE, DEALLOCATE follows this exact order. Other options mix the steps incorrectly.Final Answer:
DECLARE, OPEN, FETCH, CLOSE, DEALLOCATE -> Option CQuick Check:
Cursor lifecycle order = C [OK]
- Opening cursor before declaring
- Fetching before opening
- Not deallocating after closing
DECLARE @Name VARCHAR(50); DECLARE name_cursor CURSOR FOR SELECT Name FROM Employees WHERE Department = 'Sales'; OPEN name_cursor; FETCH NEXT FROM name_cursor INTO @Name; WHILE @@FETCH_STATUS = 0 BEGIN PRINT @Name; FETCH NEXT FROM name_cursor INTO @Name; END CLOSE name_cursor; DEALLOCATE name_cursor;
Assuming the Employees table has Sales department names: 'Alice', 'Bob', 'Carol'.
Solution
Step 1: Understand cursor fetch loop
The cursor fetches each row where Department = 'Sales'. It prints the @Name variable for each fetched row.Step 2: Identify the printed names
Since the table has 'Alice', 'Bob', and 'Carol' in Sales, all three names will be printed one by one.Final Answer:
Alice Bob Carol (each printed on a new line) -> Option DQuick Check:
Cursor prints all fetched rows [OK]
- Assuming only first row prints
- Forgetting to open cursor
- Confusing fetch status check
DECLARE cur CURSOR FOR SELECT Id FROM Products; OPEN cur; FETCH NEXT FROM cur INTO @ProductId; WHILE @@FETCH_STATUS = 0 BEGIN PRINT @ProductId; END CLOSE cur; DEALLOCATE cur;
Solution
Step 1: Check fetch inside loop
The code fetches once before the loop but does not fetch again inside the loop, causing an infinite loop.Step 2: Identify missing statement
To move to next row, FETCH NEXT must be inside the WHILE loop after PRINT.Final Answer:
Missing FETCH NEXT inside the WHILE loop -> Option AQuick Check:
Fetch inside loop needed to advance cursor [OK]
- Forgetting FETCH NEXT inside loop
- Assuming one fetch is enough
- Not opening cursor before fetch
Solution
Step 1: Understand row-by-row update need
When updating salaries individually, you must fetch each employee row and update inside the loop.Step 2: Identify correct cursor usage
Declare cursor for SELECT, open it, fetch each employee, update salary inside loop, close and deallocate correctly declares, opens, fetches, updates inside loop, then closes and deallocates cursor.Final Answer:
Declare cursor for SELECT, open it, fetch each employee, update salary inside loop, close and deallocate -> Option BQuick Check:
Cursor updates row-by-row inside loop [OK]
- Trying to update before opening cursor
- Not fetching rows before update
- Using cursor but updating all at once
Ready to prove it?
Pass the test and this pattern moves unknown
