A SQL cursor is a database object that lets you iterate through query results row-by-row; use it only when set-based operations can’t solve the problem efficiently.
A cursor is a database object that points to the result set of a query and lets you fetch, manipulate, or process each row sequentially. Think of it as a controlled, server-side iterator similar to a for
loop in procedural languages.
You define the cursor and its underlying SELECT statement.
The database materializes the result set and positions the cursor before the first row.
Each FETCH statement moves the pointer forward and returns the current row to your session.
You execute procedural logic-updates, calculations, API calls-on the fetched row.
When finished, you release server memory and locks.
Use a cursor only when row-by-row processing is truly required, such as:
If the task can be expressed as a single INSERT-SELECT, UPDATE-JOIN, or window function, choose the set-based approach-it’s faster and easier to maintain.
Performance overhead: Each FETCH incurs context switching and locking, often making cursors 10×–100× slower than set operations.
Resource usage: They hold memory and may escalate locks, blocking other queries.
Complexity: Procedural code is harder to read, test, and optimize.
Most cursor use cases can be rewritten with common table expressions, window functions, or MERGE statements. Tools like the Galaxy SQL editor surface query plans and suggest set-based rewrites via its AI copilot, so you can eliminate slow cursors in seconds.
What are set-based operations in SQL?; How do window functions replace cursors?; What is the difference between a cursor and a loop in T-SQL?; How to optimize slow SQL scripts?
Check out the hottest SQL, data engineer, and data roles at the fastest growing startups.
Check outCheck out our resources for beginners with practice exercises and more
Check outCheck out a curated list of the most common errors we see teams make!
Check out