Database cursor

On this page 7

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.

PhaseWhat happensResources involved
DeclareAssociates a name with a query and optionsMetadata only
OpenExecutes the query and positions before the first rowExecution plan, memory, possibly locks
FetchReturns the current row into variables and moves the positionNetwork round trip or buffer read
CloseReleases the result set but keeps the definitionFrees memory and most locks
DeallocateRemoves the cursor definition entirelyFrees remaining metadata
Phases of the cursor lifecycle

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 typeScrollingSees concurrent changesTypical cost
Forward-onlyNext row onlyDepends on isolation levelLowest
Static (insensitive)FullNo, works on a snapshot copyHigh memory or tempdb use
Keyset-drivenFullUpdates yes, new inserts noModerate
DynamicFullYes, membership can changeHighest per fetch
Fast forwardNext row onlyRead-only, optimizedVery low
Common cursor types compared

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.

TaskPreferred approachReason
Apply the same price change to many rowsSingle UPDATEOne statement, one plan, minimal overhead
Running totals over ordered rowsWindow functionComputed in one pass without loops
Call an external procedure per rowCursorEach row needs a separate procedural call
Stream millions of rows to a clientServer-side forward-only cursorLimits memory on both sides
Paginate a web listingKeyset pagination queryStateless and scales better than an open cursor
Choosing between cursor logic and set-based statements

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.

SymptomLikely causeFix
Batch job runs for hoursRow-by-row updates in a cursor loopRewrite as one set-based statement
Other sessions are blockedLong-lived cursor holding locksUse a read-only cursor and shorter transactions
Error about too many open cursorsCursors not closed in error pathsClose in a finally block or context manager
Application runs out of memoryClient-side cursor on a huge resultSwitch to a server-side cursor with a fetch size
Rows appear twice or are skippedUpdating the sort key during a dynamic cursor scanUse a static or keyset cursor
Cursor symptoms, causes and fixes

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.