Cursor
In one line
A cursor iterates over query results one row at a time — useful for large datasets that don't fit in memory.
In simple words
A cursor is a database control structure that lets you retrieve query results one row at a time instead of loading all rows into memory at once. It's like a pointer that moves through the result set.
Use cases:
- Large result sets — process millions of rows without OOM
- Row-by-row processing — apply logic per row before moving to next
- Pagination — fetch chunks of data
- Batch updates — process and update in batches
In SQL, you DECLARE, OPEN, FETCH (loop), and CLOSE a cursor. In MongoDB, cursors are returned automatically from find(). Cursors hold server-side state and should always be closed to release resources.
Example
-- SQL cursor example
DECLARE user_cursor CURSOR FOR
SELECT id, name FROM users WHERE active = 1;
OPEN user_cursor;
DECLARE @id INT, @name VARCHAR(100);
FETCH NEXT FROM user_cursor INTO @id, @name;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'Processing: ' + @name;
FETCH NEXT FROM user_cursor INTO @id, @name;
END
CLOSE user_cursor;
DEALLOCATE user_cursor;The cursor iterates through active users one at a time. FETCH NEXT gets each row; @@FETCH_STATUS = 0 means a row was retrieved.
Common confusions
Confused with: iterator
The difference: An iterator is a programming language construct for traversing collections in memory. A cursor is a database object that traverses server-side query results. Cursors involve network round-trips per fetch; iterators work in local memory. Both do sequential access but at different levels.
Related terms
Related Resources
Related Lessons
- SQL Advanced
Cursors.
Decode error messages
Plain-English explanations of common errors — what they mean, why they happen, and how to fix them.