A database cursor is a control structure that points to a position within a query result set, allowing an application or a stored procedure to fetch, examine and optionally modify rows one at a time instead of handling the whole result as a single block. Among the database fundamentals, the cursor is the mechanism that bridges set-based SQL and record-at-a-time procedural code.
Every relational DBMS uses cursors internally, even when the programmer never declares one: a client library that iterates over the rows of a SELECT statement is reading from a cursor. Explicit cursors appear in procedural extensions such as PL/SQL, Transact-SQL and PL/pgSQL, and in client interfaces such as ODBC, JDBC and the Python DB-API.
How a database cursor moves through a result set
A cursor follows a fixed lifecycle of declare, open, fetch and close. The declaration binds the cursor to a query; opening it executes the query and establishes the result set; each fetch returns the current row and advances the position; closing it releases memory, locks and server resources.
The SQL standard defines this sequence with the statements DECLARE CURSOR, OPEN, FETCH and CLOSE, and a later DEALLOCATE in some products. Inside a loop, the program tests a status indicator, such as @@FETCH_STATUS in Transact-SQL or the %NOTFOUND attribute in PL/SQL, to detect the end of the result set.
The table below summarizes each phase and the resources it touches.
| Phase | What happens | Resources involved |
|---|---|---|
| Declare | Associates a name with a query and options | Metadata only |
| Open | Executes the query and positions before the first row | Execution plan, memory, possibly locks |
| Fetch | Returns the current row into variables and moves the position | Network round trip or buffer read |
| Close | Releases the result set but keeps the definition | Frees memory and most locks |
| Deallocate | Removes the cursor definition entirely | Frees remaining metadata |
A cursor can also be positioned for updates. With the clause WHERE CURRENT OF cursor_name, an UPDATE or DELETE statement affects exactly the row the cursor currently points to, which avoids re-identifying the row through its primary key.
Types of cursors and their behavior
Cursors differ in scrolling ability and sensitivity to concurrent changes. A forward-only cursor can move in one direction only, whereas a scrollable cursor supports FETCH PRIOR, FETCH FIRST, FETCH LAST and FETCH ABSOLUTE n. Sensitivity determines whether changes committed by other transactions become visible while the cursor is open.
The following comparison lists the cursor models defined by ODBC and Transact-SQL, which other systems approximate under different names.
| Cursor type | Scrolling | Sees concurrent changes | Typical cost |
|---|---|---|---|
| Forward-only | Next row only | Depends on isolation level | Lowest |
| Static (insensitive) | Full | No, works on a snapshot copy | High memory or tempdb use |
| Keyset-driven | Full | Updates yes, new inserts no | Moderate |
| Dynamic | Full | Yes, membership can change | Highest per fetch |
| Fast forward | Next row only | Read-only, optimized | Very low |
A further distinction separates server-side cursors, which keep the result set on the database server and send rows on request, from client-side cursors, which transfer the entire result to the application and iterate locally. Server-side cursors save client memory on large results; client-side cursors free the server sooner but can exhaust application memory.
Some products also offer holdable cursors, declared WITH HOLD, which remain open after the transaction that created them commits. Without this option, a commit normally closes every open cursor.
Cursors compared with set-based SQL
Set-based SQL is usually faster than cursor processing because the optimizer can process an entire set at once, choose join algorithms, use parallelism and minimize logging. A cursor forces row-by-row execution, often called RBAR, row by agonizing row, which multiplies per-row overhead such as context switches, lock acquisitions and log records.
The next table matches common tasks with the preferred approach.
| Task | Preferred approach | Reason |
|---|---|---|
| Apply the same price change to many rows | Single UPDATE | One statement, one plan, minimal overhead |
| Running totals over ordered rows | Window function | Computed in one pass without loops |
| Call an external procedure per row | Cursor | Each row needs a separate procedural call |
| Stream millions of rows to a client | Server-side forward-only cursor | Limits memory on both sides |
| Paginate a web listing | Keyset pagination query | Stateless and scales better than an open cursor |
A cursor is therefore a tool for genuinely procedural work, such as administrative scripts that run dynamic SQL against each table in a schema, or workflows that must call a stored procedure for each row with side effects.
Cursors in application code
Most developers meet cursors through client database interfaces. In the Python DB-API, connection.cursor() returns a cursor object whose execute, fetchone, fetchmany and fetchall methods map directly to the lifecycle. In JDBC, the ResultSet object plays the same role, and its type constants select forward-only or scrollable behavior.
The fetch size is the main tuning parameter in client code. Fetching one row per round trip over a network with 1 ms latency limits throughput to roughly one thousand rows per second, while a fetch size of a few hundred to a few thousand rows amortizes latency without excessive memory use.
- PostgreSQL drivers often load the full result unless a named server-side cursor or a fetch size inside a transaction is used.
- Object-relational mapping libraries usually hide cursors but expose streaming or chunked iteration for large results.
- Connection pools require that cursors are closed before the connection returns to the pool.
Limitations and common mistakes
Cursor problems typically surface as slow batch jobs, blocking and resource leaks. The following table connects frequent symptoms with their causes and remedies.
| Symptom | Likely cause | Fix |
|---|---|---|
| Batch job runs for hours | Row-by-row updates in a cursor loop | Rewrite as one set-based statement |
| Other sessions are blocked | Long-lived cursor holding locks | Use a read-only cursor and shorter transactions |
| Error about too many open cursors | Cursors not closed in error paths | Close in a finally block or context manager |
| Application runs out of memory | Client-side cursor on a huge result | Switch to a server-side cursor with a fetch size |
| Rows appear twice or are skipped | Updating the sort key during a dynamic cursor scan | Use a static or keyset cursor |
A frequent misconception is that a cursor guarantees a consistent view of the data. Consistency depends on the transaction isolation level and the cursor type, so a dynamic cursor under read committed isolation may legitimately return rows that did not exist when it was opened.
The short version
A database query often returns many rows at once. A cursor is like a bookmark that lets a program read those rows one at a time, in order, and do something with each one before moving on.
This is useful when each row needs individual handling, but it is slower than telling the database to change all matching rows in one instruction. Use a cursor when individual steps are truly necessary, and let the database handle whole groups whenever possible.
Where it makes a difference
A logistics company keeps 40 million shipment records in a relational database and must export them nightly to a data warehouse. The first version of the export script loaded the whole query result into the application, which consumed more than 30 GB of memory and frequently crashed the export server.
The team replaced it with a server-side forward-only cursor and a fetch size of 5,000 rows, writing each batch to a compressed file before fetching the next one. Memory use dropped below 500 MB, and the export finished in about the same time because network round trips remained few.
In the same project, a separate maintenance script used a cursor loop to update a status flag on every delivered shipment. Replacing that loop with one set-based UPDATE statement cut its run time from about two hours to under four minutes, which illustrates both the proper use and the misuse of cursors.