Curious Minds

Clear answers to science and history questions

PostgreSQL Cursors and FETCH: How They Work

· 7 min read · Science

In PostgreSQL, a cursor is a database object that allows you to retrieve a result set one row at a time, and FETCH is the command that retrieves the next row(s) from that cursor. Cursors are used inside transactions (or with holdable cursors that survive commit) to process large result sets without loading everything into memory at once, and they are especially useful in procedural code and client applications that need row-by-row control.

What a Cursor Actually Is in PostgreSQL

A cursor is not a separate storage structure; it is a pointer to a query's result set that the server materializes (or streams) and keeps open for the duration of a transaction. When you declare a cursor, PostgreSQL parses and plans the query but does not execute it immediately. Execution begins when you first fetch from the cursor, and the server may use a portal—an internal execution state—to track how far you have read. Cursors come in two flavors: without hold, which are closed automatically at the end of the transaction, and with hold, which remain open after commit but are read-only and cannot be used with certain query types.

Because a cursor holds a snapshot of the data as of the time the cursor was opened, concurrent changes made by other transactions after that point are not visible through the cursor. This snapshot behavior is a key reason cursors are used for consistent, long-running reads, but it also means a cursor can hold back vacuum cleanup of old row versions for as long as it stays open.

How to Declare and Use a Cursor

The basic lifecycle involves four SQL commands: DECLARE, FETCH, MOVE, and CLOSE. Here is a minimal example:

  1. BEGIN; — start a transaction. Cursors without hold require an explicit transaction block.
  2. DECLARE my_cursor CURSOR FOR SELECT id, name FROM users ORDER BY id; — declare the cursor. The query is not executed yet.
  3. FETCH FORWARD 10 FROM my_cursor; — retrieve the first 10 rows. The cursor position advances.
  4. FETCH NEXT FROM my_cursor; — retrieve the next single row.
  5. CLOSE my_cursor; — release the cursor.
  6. COMMIT; — end the transaction; any non-holdable cursors are closed automatically.

You can also declare a cursor with options such as SCROLL (allows backward fetching), NO SCROLL (forward-only, the default for most queries), and WITH HOLD (survives commit). For example: DECLARE c SCROLL CURSOR WITH HOLD FOR SELECT * FROM orders;.

FETCH Variants and Positioning

FETCH is more flexible than simply grabbing the next row. The full syntax allows a direction and a count:

  • FETCH NEXT or FETCH FORWARD 1 — the default, one row forward.
  • FETCH PRIOR — one row backward (requires a SCROLL cursor).
  • FETCH FIRST — the first row of the result set.
  • FETCH LAST — the last row (SCROLL only).
  • FETCH ABSOLUTE n — the n-th row from the start (SCROLL only).
  • FETCH RELATIVE n — n rows from the current position (SCROLL only).
  • FETCH ALL — all remaining rows.
  • FETCH FORWARD n — the next n rows.

The MOVE command works like FETCH but repositions the cursor without returning rows, which is useful for skipping ahead efficiently. After each FETCH, the cursor position advances, and a subsequent FETCH continues from there. If you fetch past the end, you get zero rows and the cursor remains after the last row; fetching backward from there returns rows again if the cursor is scrollable.

Scrollable vs. Non-Scrollable Cursors

By default, PostgreSQL creates a non-scrollable cursor for most queries, meaning you can only move forward. Declaring SCROLL enables backward movement and absolute positioning, but it may require the server to materialize the entire result set in memory or temporary storage, which can be expensive for large results. Some queries—such as those with volatile functions or certain joins—cannot be made scrollable, and PostgreSQL will raise an error if you try. In practice, forward-only cursors are the common choice for streaming large result sets, while scrollable cursors suit interactive applications that need random access.

Cursors in PL/pgSQL and Client Applications

Inside PL/pgSQL, you can use a FOR loop over a query without explicitly declaring a cursor; PostgreSQL handles the cursor internally. For explicit control, you can declare a cursor variable and use OPEN, FETCH, and CLOSE statements. This is handy when you need to process rows in batches or interleave logic between fetches.

Client libraries also expose cursors. In Python's psycopg2, for example, you can create a named cursor with conn.cursor(name='my_cursor'), which uses a server-side cursor and fetches rows in chunks via fetchmany(). This avoids loading the entire result set into client memory. Similarly, JDBC supports setFetchSize() to control how many rows the driver retrieves at a time, though true server-side cursors require autocommit to be off and a specific result set type.

Performance and Resource Considerations

Cursors are not free. Each open cursor consumes server memory and, for scrollable or holdable cursors, may spill to disk. A long-lived cursor can prevent vacuum from cleaning up dead tuples, leading to table bloat. Holdable cursors are materialized at commit time, which can be costly for large result sets. Also, fetching row-by-row over a network is far slower than retrieving a set-based result in one query; cursors are best when you genuinely need incremental processing or must limit memory use.

Another subtlety: cursors see a snapshot taken at the time the cursor is opened (or at the time of the first FETCH for some cases). If you need to see changes made by other transactions during a long read, a cursor is the wrong tool—use a new query instead.

Common Problems and Misconceptions

  • “Cursors are always server-side.” In many client libraries, a cursor object may simply buffer the entire result set on the client. Check your driver's documentation; named cursors in psycopg2 are server-side, but unnamed ones are not.
  • “I can use a cursor outside a transaction.” Without WITH HOLD, a cursor exists only within the transaction that declared it. In autocommit mode, the transaction ends immediately, so the cursor disappears.
  • “FETCH ALL is always fine.” Fetching all rows from a huge cursor defeats the purpose and can exhaust memory.
  • “Cursors are updatable.” PostgreSQL cursors are read-only; you cannot use WHERE CURRENT OF to update through a cursor as some other databases allow.

A frequent error is cursor “x” does not exist, usually caused by declaring the cursor in a transaction that has already ended, or by a typo in the cursor name. Another is cursor can only scan forward, which means you tried a backward fetch on a non-scrollable cursor.

Frequently Asked Questions

Can I use a cursor without an explicit transaction?

No, a cursor declared without WITH HOLD requires an open transaction. In autocommit mode, each statement is its own transaction, so the cursor is closed as soon as the declaring statement finishes. Use BEGIN to start a transaction block, or declare the cursor WITH HOLD if it must survive commit.

What is the difference between FETCH and SELECT?

SELECT executes a query and returns the entire result set (or as much as the client requests). FETCH retrieves rows from an already-declared cursor, advancing its position. FETCH does not re-run the query; it reads from the cursor's stored execution state.

Are PostgreSQL cursors updatable?

No. PostgreSQL cursors are read-only. You cannot use UPDATE ... WHERE CURRENT OF cursor_name as you can in some other database systems. To modify rows, you must identify them by primary key or another criterion and run separate UPDATE statements.

How do I fetch rows in batches?

Use FETCH FORWARD n FROM cursor_name repeatedly, where n is your batch size. In client libraries, methods like fetchmany(size) on a named cursor achieve the same effect. Always close the cursor when done to free resources.

Do cursors see changes made by other transactions?

No. A cursor operates on a snapshot of the data taken when it is opened (or at first fetch, depending on the query). Changes committed by other transactions after that point are not visible through the cursor. This provides consistency but means cursors are not suitable for real-time monitoring of changing data.

What happens if I forget to close a cursor?

Non-holdable cursors are closed automatically at the end of the transaction. Holdable cursors persist until explicitly closed or until the session ends. However, leaving cursors open can hold resources and, in the case of holdable cursors, prevent vacuum from reclaiming space. It is good practice to close cursors explicitly.

In this article
  1. What a Cursor Actually Is in PostgreSQL
  2. How to Declare and Use a Cursor
  3. FETCH Variants and Positioning
  4. Scrollable vs. Non-Scrollable Cursors
  5. Cursors in PL/pgSQL and Client Applications
  6. Performance and Resource Considerations
  7. Common Problems and Misconceptions
  8. Frequently Asked Questions