Skip to content

Cursors & Streaming Results ​

"Ordinarily, libpq collects an SQL command's entire result and returns it to the application as a single PGresult. This can be unworkable for commands that return a large number of rows." — PostgreSQL 19 Documentation, §32.6 Retrieving Query Results in Chunks (libpq)

Summary: A big result set must never be "loaded"; it must flow through the application in small pieces, and a cursor (or a driver's streaming mode) is the mechanism that makes it flow. Focus: Client-side vs server-side cursors, DECLARE/FETCH/WITH HOLD, driver buffering in PostgreSQL, MySQL, Go and Laravel, the transaction cost of an open cursor, and streaming exports to CSV, S3 and HTTP. Learning goal: Pick the right way to read millions of rows (keyset, cursor, single-row mode, COPY), predict the memory and locks it costs, and write an export handler that stops when the client leaves.

This page is the complete reference for reading large result sets without blowing up memory: what a cursor is, why most drivers buffer by default, how PostgreSQL portals, MySQL unbuffered queries, SQL Server cursor types and Oracle ref cursors differ, what an open cursor costs the database (a transaction, a snapshot, locks, bloat), and how to stream the rows out to a CSV file, S3 or an HTTP response with backpressure and cancellation. It deliberately does not re-teach its neighbours. Offset vs keyset paging for user-facing lists is in Pagination; snapshots, xmin and dead tuples are in MVCC, VACUUM & Bloat; the cursor lost update anomaly and Cursor Stability are in Isolation Levels; lock modes are in Locks & Concurrency; and what happens to a session behind PgBouncer is in Connection Pooling. The next chapter, Working with Billion-Row Tables, builds on this one.

Page map ​

If you are looking forGo to
The one-minute tablesEverything in one minute
Why a plain SELECT can kill your processWhy cursors and streaming exist
Client-side vs server-side cursor, result set bufferingClient-side vs server-side
DECLARE, FETCH FORWARD n, MOVE, CLOSE, SCROLL, portalPostgreSQL cursors in depth
WITH HOLD vs WITHOUT HOLD, cursor and transaction lifetimeCursor lifetime
What an open cursor costs: idle in transaction, locks, snapshot, bloatThe price of an open cursor
libpq single-row mode, chunked mode, pipeline mode, pgx, JDBC fetch sizeDriver-level streaming
MySQL unbuffered queries, "Commands out of sync", SQL Server cursor types, Oracle ref cursors, MongoDB, SQLiteWhat each database really does
Cursor stability, cursor lost update, WHERE CURRENT OFCursor stability and updatable cursors
Laravel cursor() vs lazy() vs lazyById(), Go rows.Next()Application-level streaming
COPY vs SELECT, CSV/S3/HTTP exports, NDJSON, backpressureStreaming exports
Keyset vs cursorKeyset vs cursor
Retry and failure handling mid-streamFailure handling while streaming
Which technique for which jobChoosing
Monolith to distributed systemIn architecture
Reproduce it in two terminalsLab

Everything in one minute ​

The vocabulary. Every row is unpacked later.

TermIn plain wordsWhere it lives
Client-side cursor / buffered resultThe driver downloads all rows first; your loop walks a local arrayDriver memory (libpq PGresult, mysqlnd store-result, PHP PDO buffer)
Server-side cursorThe server keeps the query position; you ask for rows in batchesA portal in the database session
PortalThe server's execution state for one running statement or cursorPostgreSQL backend memory
DECLARE / FETCH / MOVE / CLOSECreate the cursor / get rows / skip rows / destroy itSQL (PostgreSQL, SQL Server, MySQL stored programs, Oracle PL/SQL)
WITHOUT HOLDCursor dies at COMMIT (default)PostgreSQL
WITH HOLDCursor survives COMMIT; rows are copied to temp storagePostgreSQL
Single-row modelibpq hands you one row at a time as it arrives from the socketlibpq, pgx, any driver built on it
Fetch size / batch sizeHow many rows per round tripJDBC setFetchSize, FETCH FORWARD n, Oracle array size
BackpressureA slow consumer slows the producer instead of filling memoryTCP window, ClientWrite wait event, blocking Write
Keyset paginationNext page = WHERE id > :last ORDER BY id LIMIT n, no server statePlain SQL

The four ways to read a lot of rows.

TechniqueServer state keptMemory in clientNeeds a long transaction?Best for
SELECT all, buffered (default driver behaviour)None after the result is sentWhole resultNoSmall results (< ~10k rows)
Streaming a plain SELECT (pgx Rows, libpq single-row, MySQL unbuffered)The running statement, until the last row is readOne row or one network bufferThe statement itself acts as oneOne-pass processing, exports
DECLARE + FETCH FORWARD nA portal and a snapshot, across statementsOne batchYes (unless WITH HOLD)Batch jobs that interleave work between batches
Keyset chunks (lazyById, WHERE id > :last LIMIT n)Nothing between chunksOne chunkNo: each chunk is its own short transactionLong jobs, jobs that update what they read

The things to do.

SituationDo this
Export millions of rows to CSVCOPY (SELECT ...) TO STDOUT WITH (FORMAT csv) and pipe the bytes; do not build objects per row
Process millions of rows in Gorows.Next() loop with ctx; defer rows.Close(); check rows.Err()
Process millions of rows in LaravellazyById(2000) (or chunkById), not all()/get(); cursor() only if you understand the PDO buffer
A cursor must outlive its transactionDECLARE ... WITH HOLD, and CLOSE it yourself
Anything streaming for minutesSet idle_in_transaction_session_timeout, statement_timeout, a read replica, and cancel on client disconnect

Why cursors and streaming exist ​

A query returns a result set. Between the database and your code sit several buffers: the server's send buffer, the TCP window, the driver's receive buffer, the driver's result object, and finally your own objects (structs, Eloquent models, maps). The default in almost every driver is to drain all of it into the driver's result object before your first rows.next() returns. That is a good default for 50 rows, because the connection becomes free immediately, you can ask count($rows), and you can run another query while iterating. It is a disaster for 50 million rows: memory is spent before you have done any work, the process may be killed by the OOM killer (Linux oom-killer, a PHP Allowed memory size of ... bytes exhausted fatal error, a Kubernetes OOMKilled pod), and the first byte of the response is delayed until the last row arrived.

Buffer it all (simple)Stream it (bounded)
Memory grows with the result sizeMemory is one row or one batch
First row available only after the last row is downloadedFirst row available after the first network packet
Connection free immediatelyConnection busy until the last row is read (or you cancel)
Row count known up frontRow count known only at the end
Server work is done fast, then you take your timeServer work and your work are coupled: slow consumer, slow query
No long-lived transaction or snapshotStatement, snapshot and locks stay alive as long as you stream

The analogy we reuse on this page: a water tank vs a hose. Buffering is filling a tank from a reservoir and then drinking from it: you need a tank as big as the reservoir. Streaming is drinking straight from a hose: you need no tank, but the reservoir's valve stays open while you drink, and if you walk away with the hose running you flood the garden (an open transaction pinned for hours). A cursor is a tap with a handle: you decide how much comes out per turn.

Three common misunderstandings, up front ​

  1. "foreach over the result is streaming." Not unless the driver is streaming. In PHP with pdo_mysql, PDO's default is a buffered query: the whole result is already in PHP memory before your first foreach iteration. Laravel's own documentation says so for cursor(): "it will still eventually run out of memory. This is due to PHP's PDO driver internally caching all raw query results in its buffer."
  2. "A cursor is a cheap way to read less." A server-side cursor reads exactly as much as the query needs, but it keeps a transaction, a snapshot and often locks alive between your FETCH calls. Memory moves from the client to the server's transaction state, and the price becomes bloat and lock waits.
  3. "cursorPaginate() and cursor() are the same thing." In Laravel, cursorPaginate() is keyset pagination (an opaque "cursor" token for the next page, no server state), while cursor() iterates a single statement with a PHP generator. A database cursor is a third thing. The word "cursor" means three different mechanisms; this page keeps them apart.

Client-side vs server-side cursors Must-know ​

In plain words: a client-side "cursor" is just a loop over rows the driver already downloaded. A server-side cursor is a bookmark kept by the database: it remembers where the query stopped and gives you the next batch when you ask.

Common misunderstanding: "Using rows.Next() / fetch() / foreach means I have a server-side cursor." No. Those APIs iterate the driver's buffer or the socket. A server-side cursor exists only if the SQL (DECLARE), the wire protocol (extended-protocol Execute with a row limit, which pgjdbc uses when fetchSize is set) or a driver option (MySQL useCursorFetch) creates it.

Definition: a result set buffer holds rows already received from the server. A client-side cursor reads rows from that buffer. A server-side cursor is a server object (PostgreSQL: a portal; SQL Server: an API server cursor or DECLARE CURSOR; Oracle: an open cursor in the shared server process; MySQL: a read-only, non-scrollable cursor materialised for a stored program or a prepared statement) that produces rows on demand. Streaming (single-row mode, MySQL unbuffered, pgx Rows) is a third case: the statement runs normally, but the driver hands rows to you as they arrive from the socket instead of collecting them first.

text
     CLIENT-SIDE (buffered)                    SERVER-SIDE CURSOR
1    send "SELECT * FROM orders"               BEGIN;
2    server sends 10M rows ------------>       DECLARE c CURSOR FOR SELECT * FROM orders;
3    driver stores all 10M in RAM              FETCH FORWARD 2000 FROM c;   -- 2000 rows, then stop
4    app loop starts                           (app works on 2000 rows)
5    app reads row 1 ... row 10M               FETCH FORWARD 2000 FROM c;   -- next 2000
6    memory = whole result                     ...  memory = one batch
7                                              CLOSE c; COMMIT;
A. Buffered (default): whole result lands in client memoryServerexecutes query,sends ALL rowsDriver buffer (libpq PGresult,mysqlnd store_result)10M rows = GBs of RAMApplicationfirst row after thelast one arrivedall rowsrow by rowB. Server-side cursor / single-row mode: bounded memory, backpressureServerPortal / cursor positionsnapshot + locks heldrows not yet producedstay on the serverSmall batchFETCH 2000 / 1 rowApplicationprocess row, write toCSV / socket, then askfor the next batchslow client = slow fetchnext FETCH / read from socket (client pace sets server pace)

Real scenario:

  • A nightly "export all customers" job works for a year, then the table passes 20 million rows and the container is OOMKilled at 3 a.m.; nothing in the code changed except the data.
  • A reporting endpoint returns 500k rows as JSON; the PHP-FPM worker hits memory_limit and returns an HTTP 500 after 40 seconds of silence.
  • A Go service builds []Order before writing a CSV; the garbage collector spends most of the CPU re-scanning a 3 GB heap and tail latencies of unrelated requests double.
  • A data-migration script does SELECT * on the source and INSERT on the target; the source driver buffers everything first, so the copy cannot start until the source has sent everything.
What prevents itPostgreSQLMySQLSQL ServerOracle
Driver streaming a plain statementlibpq single-row/chunked mode, pgx Rowsmysql_use_result, MYSQLI_USE_RESULT, PDO::MYSQL_ATTR_USE_BUFFERED_QUERY = false, go-sql-driver reads packets lazilyDefault result set ("firehose") streams; one active result per connection unless MARSFetch in array-size batches (the driver's prefetch)
SQL-level cursorDECLARE ... CURSOROnly inside stored programs (DECLARE cur CURSOR FOR)DECLARE ... CURSOROPEN cur FOR / SYS_REFCURSOR in PL/SQL
Protocol-level cursorExtended protocol Execute with max rows (portal suspended)Prepared-statement cursor (CURSOR_TYPE_READ_ONLY, useCursorFetch)API server cursors (ODBC/OLE DB)OCI fetch with array size

Fix / how to use it: the full code is in Application-level streaming. In SQL:

sql
BEGIN;
DECLARE orders_cur NO SCROLL CURSOR FOR
    SELECT id, customer_id, total_cents FROM orders ORDER BY id;
FETCH FORWARD 2000 FROM orders_cur;   -- repeat until fewer than 2000 rows come back
CLOSE orders_cur;
COMMIT;
go
// Go: stream a plain SELECT; pgx reads rows off the socket as you call Next().
rows, err := db.QueryContext(ctx, `SELECT id, total_cents FROM orders ORDER BY id`)
if err != nil { return err }
defer rows.Close()
for rows.Next() { /* Scan, process */ }
return rows.Err()
php
// Laravel: cursor() is a generator over ONE statement; lazyById() is many keyset queries.
foreach (DB::table('orders')->orderBy('id')->lazyById(2000) as $row) { /* ... */ }

PostgreSQL cursors in depth ​

PostgreSQL's SQL-level cursor commands are DECLARE, FETCH, MOVE and CLOSE. The manual's synopsis is DECLARE name [ BINARY ] [ ASENSITIVE | INSENSITIVE ] [ [ NO ] SCROLL ] CURSOR [ { WITH | WITHOUT } HOLD ] FOR query. PL/pgSQL has its own cursor variables (refcursor, OPEN, FETCH ... INTO, MOVE, CLOSE) and the implicit cursor behind FOR rec IN query LOOP.

Portal Important ​

In plain words: a portal is the server-side object that holds "this query, paused here". Every statement runs inside one; a cursor is just a portal with a name that you can come back to.

Common misunderstanding: "A portal is a PostgreSQL cursor and only exists if I DECLARE one." The extended query protocol creates an unnamed portal for every Bind/Execute; DECLARE creates a named portal that outlives the statement. The PL/pgSQL manual states: "Opening a cursor involves creating a server-internal data structure called a portal, which holds the execution state for the cursor's query."

Definition: a portal has a name unique within the session and lives until it is closed, until its transaction ends (WITHOUT HOLD), or until the session ends (WITH HOLD). A refcursor value is "simply the string name of the portal", so it can be passed around, but "All portals are implicitly closed at transaction end."

text
     CLIENT                                    SERVER (extended protocol)
1    Parse   "SELECT ... FROM orders"   ---->  prepared statement
2    Bind    (params) -> portal ""      ---->  portal created
3    Execute portal "" max_rows=1000    ---->  runs, returns 1000 DataRow messages
4                                        <---  PortalSuspended ('s')
5    Execute portal "" max_rows=1000    ---->  next 1000 rows
6                                        <---  CommandComplete after the last row
7    Sync                               ---->  ReadyForQuery (transaction ends if implicit)

Real scenario: pgjdbc with setFetchSize(1000) and autocommit off uses exactly this Execute(max_rows) / PortalSuspended loop, which is why "fetch size does nothing in autocommit mode" is a famous JDBC pitfall: without a surrounding transaction the unnamed portal cannot survive between executes. psql does the same with \set FETCH_COUNT 10000: it wraps your query in a cursor and prints in batches, so SELECT * FROM big_table no longer fills psql's memory.

QuestionAnswer
Can two cursors be open in one session?Yes, each is its own named portal
Where can I see them?SELECT * FROM pg_cursors; (name, statement, is_holdable, is_binary, is_scrollable, creation_time)
Do portals survive ROLLBACK?No; a WITH HOLD cursor created in an aborted transaction is removed too
Do they work behind PgBouncer transaction pooling?Not across transactions; see architecture

Fix / how to use it:

sql
SELECT name, statement, is_holdable, is_scrollable, creation_time FROM pg_cursors;

DECLARE, FETCH, MOVE, CLOSE, SCROLL Must-know ​

In plain words: DECLARE creates the bookmark, FETCH reads rows from it and moves it, MOVE moves it without returning rows, CLOSE throws it away.

Common misunderstanding: "FETCH re-runs my query." No: the query was planned at DECLARE and executes incrementally; each FETCH continues where the last one ended. The result is also not refreshed: PostgreSQL cursors are insensitive. The manual: "In PostgreSQL, all cursors are insensitive; so these key words [ASENSITIVE/INSENSITIVE] have no effect and are only accepted for compatibility with the SQL standard." Changes made after DECLARE are invisible to the cursor.

Definition: FETCH [direction] [FROM|IN] cursor. Directions: NEXT (default), PRIOR, FIRST, LAST, ABSOLUTE n, RELATIVE n, n / FORWARD n, FORWARD ALL, ALL, BACKWARD n, BACKWARD ALL. MOVE takes the same directions but returns only a count. CLOSE name or CLOSE ALL frees portals early.

OptionEffectCost / caveat
NO SCROLLForward only; no backward fetchCheapest; the right default for batch jobs
SCROLLBackward and absolute fetches allowed"might impose a performance penalty"; plans may materialise results
(neither)Scrolling allowed only if the plan is simple enoughDo not rely on backward fetch without SCROLL
BINARYBinary instead of text formatObsolete under the extended protocol, where Bind chooses the format
FETCH ABSOLUTE nJump to row nNot faster than relative moves: the server walks the intermediate rows; negative values read to the end
FETCH ABSOLUTE 0Rewind to the startFast
FETCH FORWARD 0 / FETCH 0Re-fetch the current rowHandy to re-read after an UPDATE ... WHERE CURRENT OF

Timeline (batch loop with FETCH FORWARD n):

text
     SESSION A                                         NOTES
1    BEGIN;
2    DECLARE c NO SCROLL CURSOR FOR
       SELECT id FROM orders ORDER BY id;              -- planned now, nothing read yet
3    FETCH FORWARD 3 FROM c;                           -- id 1,2,3
4    MOVE FORWARD 100 IN c;                            -- "MOVE 100": skip, no rows returned
5    FETCH FORWARD 3 FROM c;                           -- id 104,105,106
6    FETCH BACKWARD 1 FROM c;                          -- ERROR: cursor can only scan forward
7    CLOSE c;
8    COMMIT;

Real scenario:

  • A billing job walks 8M invoices, calling a payment gateway for each, one batch of 500 at a time, committing its own progress table in a different connection.
  • A data-quality check uses MOVE to sample every 1000th row without transferring the rows between.
  • A reporting UI that needs "previous page" on a materialised result uses DECLARE ... SCROLL CURSOR WITH HOLD and pays for the temp copy (rare; keyset is nearly always better, see Pagination).

What provides it:

EngineCursor commandsDefaults
PostgreSQLDECLARE, FETCH, MOVE, CLOSE, pg_cursors; PL/pgSQL cursor variablesWITHOUT HOLD, insensitive, scroll only if the plan allows it
MySQL / InnoDBOnly in stored programs: DECLARE c CURSOR FOR, OPEN, FETCH ... INTO, CLOSE, handler FOR NOT FOUNDRead-only, non-scrollable, asensitive (may or may not see changes)
SQL ServerDECLARE ... CURSOR, OPEN, FETCH NEXT/PRIOR/FIRST/LAST/ABSOLUTE/RELATIVE, CLOSE, DEALLOCATE, @@FETCH_STATUSFORWARD_ONLY unless SCROLL; forward-only cursors are dynamic by default
OraclePL/SQL explicit cursors, OPEN cur FOR, BULK COLLECT ... LIMIT n, SYS_REFCURSORRead-consistent as of OPEN
SQLiteNo cursor SQL; sqlite3_step returns one row at a timeAlways streaming
MongoDBServer cursor with batchSize, getMoreFirst batch up to 101 documents, later batches up to 16 MiB; idle cursors time out after 10 minutes

Fix / how to use it:

sql
-- PL/pgSQL procedure: walk the table in keyset chunks and COMMIT after each one,
-- so no snapshot or lock is held between chunks (no cursor needed).
CREATE PROCEDURE reprice_all() LANGUAGE plpgsql AS $$
DECLARE
    last_id bigint := 0;
    max_id  bigint;
BEGIN
    LOOP
        SELECT max(id) INTO max_id
        FROM (SELECT id FROM products WHERE id > last_id ORDER BY id LIMIT 5000) s;
        EXIT WHEN max_id IS NULL;
        UPDATE products SET price_cents = price_cents * 11 / 10
        WHERE id > last_id AND id <= max_id;
        last_id := max_id;
        COMMIT;
    END LOOP;
END $$;

The Go version of the same batch loop is go/cursor/main.go below; the Laravel version is pgServerCursor() in CursorVsLazy.php.

go
// Explicit server-side cursor with pgx: DECLARE once, FETCH FORWARD n in a loop.
// Use it when you need bounded memory AND want to interleave other work (or
// other queries on the same transaction) between batches.
package main

import (
	"context"
	"fmt"
	"log"
	"os"

	"github.com/jackc/pgx/v5"
)

const batch = 2000

func main() {
	ctx := context.Background()
	conn, err := pgx.Connect(ctx, os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer conn.Close(ctx)

	tx, err := conn.BeginTx(ctx, pgx.TxOptions{IsoLevel: pgx.RepeatableRead, AccessMode: pgx.ReadOnly})
	if err != nil {
		log.Fatal(err)
	}
	defer tx.Rollback(ctx)

	// NO SCROLL: forward only, the cheapest cursor. A cursor is a named portal.
	if _, err := tx.Exec(ctx, `DECLARE c NO SCROLL CURSOR FOR
		SELECT id, total_cents FROM orders ORDER BY id`); err != nil {
		log.Fatal(err)
	}

	var total, seen int64
	for {
		rows, err := tx.Query(ctx, fmt.Sprintf("FETCH FORWARD %d FROM c", batch))
		if err != nil {
			log.Fatal(err)
		}
		n := 0
		for rows.Next() {
			var id, cents int64
			if err := rows.Scan(&id, &cents); err != nil {
				log.Fatal(err)
			}
			total += cents
			n++
		}
		if err := rows.Err(); err != nil {
			log.Fatal(err)
		}
		seen += int64(n)
		if n < batch { // short batch: cursor exhausted
			break
		}
	}
	if _, err := tx.Exec(ctx, "CLOSE c"); err != nil {
		log.Fatal(err)
	}
	if err := tx.Commit(ctx); err != nil {
		log.Fatal(err)
	}
	fmt.Printf("rows=%d total_cents=%d\n", seen, total)
}

cursor_tuple_fraction and fast-start plans Good to know ​

In plain words: the planner assumes you will read only a fraction of a cursor's rows, so it prefers a plan that returns the first rows quickly even if the total is slower.

Common misunderstanding: "DECLARE c CURSOR FOR q gets the same plan as q." Not necessarily. The manual: cursor_tuple_fraction "Sets the planner's estimate of the fraction of a cursor's rows that will be retrieved. The default is 0.1." At 1.0 "cursors are planned exactly like regular queries". With the default, the planner may pick a nested loop or an index scan that streams rows in order, where the plain query would hash-join and sort.

Definition: a GUC (SET cursor_tuple_fraction = 1.0;) that biases startup cost vs total cost. Visible with EXPLAIN DECLARE c CURSOR FOR SELECT ....

text
     QUERY                                         PLAN CHOSEN (typical)
1    SELECT ... JOIN ... ORDER BY o.id             Hash Join + Sort (best total time)
2    DECLARE c CURSOR FOR  (same SELECT)           Nested Loop over index on o.id (first rows fast)
3    SET cursor_tuple_fraction = 1.0; DECLARE ...  Hash Join + Sort again (you read it all anyway)

Real scenario: an export that reads every row but was written with a cursor runs 5x slower than the same SELECT in psql because the fast-start plan is optimal for 10% of the rows and bad for 100%. Setting cursor_tuple_fraction = 1.0 for that session fixes it.

SettingPlanner biasUse when
0.1 (default)First rows fastUI-like consumption: you will stop early
1.0Total time, like a normal queryExports and batch jobs that read everything

Fix / how to use it:

sql
SET LOCAL cursor_tuple_fraction = 1.0;   -- inside the transaction, before DECLARE
DECLARE c NO SCROLL CURSOR FOR SELECT o.id, c.email FROM orders o JOIN customers c ON c.id = o.customer_id ORDER BY o.id;

For Go and Laravel: run the SET LOCAL as the first statement in the same transaction (tx.Exec, DB::statement).

Cursor lifetime and transactions ​

WITHOUT HOLD vs WITH HOLD Must-know ​

In plain words: a normal cursor dies when its transaction ends. A WITH HOLD cursor survives the COMMIT, at the price of PostgreSQL copying the remaining rows into a temporary file or memory.

Common misunderstanding: "WITH HOLD is free and lets me keep streaming for days." It moves the cost to COMMIT and to temp storage. The manual: "In the current implementation, the rows represented by a held cursor are copied into a temporary file or memory area so that they remain available for subsequent transactions." The commit that creates it can therefore take as long as running the whole query, and a held cursor holds that space until CLOSE or the end of the session.

Definition: WITHOUT HOLD (default): "the cursor cannot be used outside of the transaction that created it", and DECLARE outside a transaction block is an error. WITH HOLD: the cursor "can continue to be used after the transaction that created it successfully commits"; it is closed by an explicit CLOSE or when the session ends; it "may not be specified when the query includes FOR UPDATE or FOR SHARE".

timeBEGINDECLARE cFETCH nFETCH nFETCH nCLOSE cCOMMITTransaction: snapshot held, row locks held (FOR UPDATE), xmin horizon pinnedWITHOUT HOLD cursor (default): portal lives here, dies at COMMITWITH HOLD: rows copied to temp storage at COMMIT, usable until CLOSE / session endDanger zone: slow consumer here = idle in transaction, VACUUM cannot clean, locks block writersROLLBACK or an error also destroys a WITHOUT HOLD cursor; a WITH HOLD cursor created in an aborted transaction is removed too.The snapshot is only released at COMMIT/ROLLBACK, not at CLOSE.
text
     SESSION A
1    BEGIN;
2    DECLARE c CURSOR WITH HOLD FOR SELECT id FROM orders ORDER BY id;
3    FETCH 2 FROM c;                  -- 1, 2     (still streaming, snapshot pinned)
4    COMMIT;                          -- rows 3..N are MATERIALISED here (can be slow)
5    FETCH 2 FROM c;                  -- 3, 4     (no transaction open any more)
6    FETCH 2 FROM c;                  -- 5, 6
7    CLOSE c;                         -- temp file freed (or on disconnect)

Real scenario:

  • A migration script commits every 10 000 updates and must keep walking the same list; WITH HOLD keeps the position across those commits. (Better: keyset on the primary key, which needs no held state.)
  • A job runs a VOLATILE function per row. The manual's trick: "declare the cursor SCROLL WITH HOLD and commit the transaction before reading any rows" to force the whole output to be materialised so each function runs exactly once per row.
  • An ETL tool opens a WITH HOLD cursor, commits to release locks and the snapshot, then reads for an hour from the copy; the source table's vacuum is no longer blocked, but the temp space is.
AspectWITHOUT HOLDWITH HOLD
Survives COMMITNoYes
Survives ROLLBACKNoNo (if created in the aborted transaction)
Snapshot / xmin pinned after COMMITN/A (cursor gone)No: the result is a copy
CostStreams from the live planCopy to temp file/memory at COMMIT (temp_file_limit applies)
With FOR UPDATEAllowed (rows locked on first fetch)Not allowed
Behind PgBouncer transaction poolingWorks only inside one transactionBreaks: next statement may hit a different server connection

Fix / how to use it:

sql
-- Release the snapshot early: materialise once, then read at leisure.
BEGIN;
DECLARE c NO SCROLL CURSOR WITH HOLD FOR SELECT id, payload FROM events WHERE created_at < now() - interval '90 days';
COMMIT;                -- pays the copy here
FETCH FORWARD 1000 FROM c;
-- ... much later, in autocommit:
CLOSE c;

Cursor and transaction lifetime Important ​

In plain words: while a normal cursor is open, your transaction is open, and everything a transaction holds (snapshot, locks, a connection) is held with it.

Common misunderstanding: "CLOSE c ends my transaction's side effects." CLOSE frees the portal; the transaction (and its snapshot and locks) lives until COMMIT or ROLLBACK.

Definition: a cursor sees the snapshot taken when it was declared (insensitive). Under READ COMMITTED the cursor's query uses that single snapshot for its whole life, even though later statements get fresh snapshots. The transaction ID horizon (backend_xmin) of the session stays pinned until the transaction ends.

text
     SESSION A (streaming)                          SESSION B (writer)
1    BEGIN;
2    DECLARE c CURSOR FOR SELECT * FROM orders;
3    FETCH 1000 FROM c;
4                                                   UPDATE orders SET status='paid' WHERE id=5;  COMMIT;
5    FETCH 1000 FROM c;    -- still sees the OLD row for id=5 (insensitive cursor)
6    SELECT status FROM orders WHERE id=5;  -- plain statement: new snapshot (READ COMMITTED) -> 'paid'
7    COMMIT;

Real scenario: a developer debugging "the cursor shows stale data" is seeing insensitivity working: the cursor is a frozen view as of DECLARE, which is also what makes an export self-consistent.

EngineWhat the cursor seesLifetime
PostgreSQLSnapshot at DECLARE (insensitive)Transaction (or CLOSE); WITH HOLD: session
MySQL stored-program cursorAsensitive: the manual says it may or may not see later changesThe program block
SQL Server STATIC / KEYSET / DYNAMIC / FAST_FORWARDFrozen copy / fixed membership / live / forward-only read-onlyUntil CLOSE/DEALLOCATE or the batch/connection ends (LOCAL vs GLOBAL)
OracleRead-consistent as of OPEN (via undo); may fail with ORA-01555 "snapshot too old"Until CLOSE

Fix / how to use it: keep the work inside the loop short and bounded, and put timeouts on the session:

sql
SET idle_in_transaction_session_timeout = '5min';   -- kill sessions that stall between FETCHes
SET statement_timeout = '30s';                      -- per FETCH, not per export
SET LOCAL transaction_timeout = '30min';            -- PostgreSQL 17+: whole transaction

Mechanics: the price of an open cursor ​

Idle in transaction while streaming Must-know ​

In plain words: between two FETCH calls your session is doing nothing, but PostgreSQL still shows it as a transaction in progress. That state is called idle in transaction.

Common misunderstanding: "If my app is slow between batches, only my app is slow." The database keeps the snapshot, the locks and a connection slot for exactly as long as your app thinks. A consumer that blocks on a slow HTTP client, a payment API or a sleep pins all three.

Definition: pg_stat_activity.state = 'idle in transaction'. statement_timeout does not fire (no statement is running); idle_in_transaction_session_timeout does, with FATAL: terminating connection due to idle-in-transaction timeout (SQLSTATE 25P03), which also destroys your cursor.

text
     SESSION A (consumer)                           pg_stat_activity (seen by DBA)
1    BEGIN;                                         state=idle in transaction, xact_start=T0
2    DECLARE c CURSOR FOR SELECT ...;               state=idle in transaction
3    FETCH 5000 FROM c;                             state=active (briefly)
4    -- app calls a slow API for 40 s                state=idle in transaction (40 s)
5    FETCH 5000 FROM c;                             state=active
6    -- app crashes mid-batch                       connection reset -> transaction rolled back

Real scenario: a webhook-sending job fetches 1000 rows per FETCH, then sends 1000 HTTP calls. Each batch takes minutes; the transaction lives for 6 hours; autovacuum cannot remove any dead tuple created after the job started.

DetectionQuery
Long-lived transactionsSELECT pid, state, now()-xact_start AS age, backend_xmin, query FROM pg_stat_activity WHERE xact_start IS NOT NULL ORDER BY xact_start;
What the stalled session waits onwait_event_type, wait_event (ClientRead = waiting for the app, ClientWrite = waiting for a slow reader)
Killing itSELECT pg_cancel_backend(pid) (cancels statement), pg_terminate_backend(pid) (drops connection)

Fix / how to use it: do the slow work outside the transaction. Read a batch, finish the transaction (or use keyset chunks), then do the slow work. SQL: idle_in_transaction_session_timeout. Go: defer tx.Rollback() plus a context deadline. Laravel: avoid DB::transaction around the whole lazy() loop; lazyById commits nothing and holds nothing between chunks when autocommit is on.

Locks held while a cursor is open Important ​

In plain words: every table the cursor reads is locked against being dropped or rebuilt until your transaction ends, and rows fetched with FOR UPDATE stay locked.

Common misunderstanding: "Reads take no locks in PostgreSQL, so an open read cursor is harmless." It takes ACCESS SHARE on each table (and index) it reads. That does not block other readers or writers, but it conflicts with ACCESS EXCLUSIVE, which ALTER TABLE, DROP, TRUNCATE, VACUUM FULL and most migrations request. The migration then waits, and every new query on that table queues behind the migration: one forgotten cursor can freeze a table.

Definition: locks acquired by a statement are held until the end of the transaction. Row locks (FOR UPDATE/FOR SHARE) are taken "at the time they are first fetched" (DECLARE manual) and "the returned rows will be the most up-to-date versions", then held until commit. Lock modes are in Locks & Concurrency.

text
     SESSION A (cursor)                         SESSION B (migration)              SESSION C (app)
1    BEGIN; DECLARE c CURSOR FOR
       SELECT * FROM orders;
2    FETCH 100 FROM c;     -- ACCESS SHARE
3                                               ALTER TABLE orders ADD COLUMN x int;
                                                -- wants ACCESS EXCLUSIVE: WAITS for A
4                                                                                  SELECT * FROM orders WHERE id=1;
                                                                                   -- queues behind B: everything stalls
5    COMMIT;               -- B proceeds, then C

Real scenario: the classic Friday deployment: a long export (cursor, 20 minutes) is running; ALTER TABLE waits; the site returns timeouts for every query on orders until someone kills the export.

EngineLock behaviour of a long read
PostgreSQLACCESS SHARE on tables and indexes until transaction end; blocks DDL (queue effect)
MySQL InnoDBPlain SELECT takes no row locks, but holds a metadata lock (MDL) until transaction end: a waiting ALTER TABLE blocks all new queries, same effect as PostgreSQL
SQL ServerREAD COMMITTED takes short shared locks per row (or none with READ_COMMITTED_SNAPSHOT); SCHEMA STABILITY (Sch-S) held; scroll-locks option on SCROLL_LOCKS cursors
OracleNo read locks; a long query may fail with ORA-01555 instead
SQLiteRead transaction; in WAL mode a long reader blocks checkpoints from finishing, so the WAL file grows

Fix / how to use it:

sql
SET lock_timeout = '3s';   -- on the MIGRATION side: give up instead of queueing everyone
ALTER TABLE orders ADD COLUMN x int;

Make long readers use a read replica, or keyset chunks (no locks held between chunks). See Zero-Downtime Schema Migrations.

Snapshot held while streaming, and the bloat pointer Important ​

In plain words: while you stream, PostgreSQL must keep every old row version your snapshot might still want, so the table cannot be cleaned and grows.

Common misunderstanding: "Bloat is a writer problem." A single idle reader can pin the cleanup horizon for the whole database: VACUUM reports tuples "dead but not yet removable" and cannot reclaim anything newer than the oldest backend_xmin.

Definition: the oldest snapshot among all sessions (backend_xmin in pg_stat_activity, plus replication slots and prepared transactions) defines the horizon. Details, VACUUM and bloat remediation are in MVCC, VACUUM & Bloat. A plain streaming SELECT also holds a snapshot for as long as the statement is "active", including time spent in ClientWrite waiting for a slow reader.

text
     STREAMING READER                          WRITERS / AUTOVACUUM
1    BEGIN; DECLARE c ...; FETCH 1000;         backend_xmin = 5000 (pinned)
2    (stalls for 2 hours)                      10M UPDATEs create dead tuples (xid 5001..9999)
3                                              autovacuum: "dead but not yet removable" = 10M
4                                              table and indexes grow (bloat), queries slow down
5    COMMIT;                                   next vacuum can finally clean; space is reusable, not returned

Real scenario: an analyst's psql with an open cursor over a hot queue table grows it from 2 GB to 40 GB in a weekend, because the queue churns millions of rows and none are removable.

Pinned bySeen inCure
Open transaction with a cursorpg_stat_activity.backend_xmin, xact_startFinish or terminate; timeouts
WITH HOLD cursorAfter commit it does not pin (copy)Prefer it if you must read slowly
Long query on a hot standbyhot_standby_feedback pushes the horizon to the primaryTurn it off for exports or use max_standby_streaming_delay knowingly
Replication slotpg_replication_slots.xmin / catalog_xminMonitor lag

Fix / how to use it:

sql
SELECT pid, now() - xact_start AS xact_age, backend_xmin, state
FROM pg_stat_activity WHERE backend_xmin IS NOT NULL ORDER BY age(backend_xmin) DESC;

Driver-level streaming ​

libpq single-row mode, chunked mode, pipeline mode Important ​

In plain words: libpq normally collects the entire result into one object. Single-row mode tells it to give you each row the moment it arrives instead.

Common misunderstanding: "Single-row mode is a server-side cursor, so it releases the snapshot." It is not: the statement is still running on the server, blocked on sending, and the snapshot is held until the last row is read. It saves client memory only.

Definition: call PQsetSingleRowMode or PQsetChunkedRowsMode(conn, n) immediately after PQsendQuery. The manual: rows "are returned to the application as they are received from the server, one at a time for single-row mode or in groups for chunked mode"; each result has status PGRES_SINGLE_TUPLE / PGRES_TUPLES_CHUNK, and the final zero-row PGRES_TUPLES_OK plus a NULL from PQgetResult end the sequence. The mode "reverts to normal after completion of the current query". Pipeline mode (PQenterPipelineMode) is a different feature: it lets you send several queries without waiting for each result, cutting round trips; with pipelines, single-row or chunked mode must be activated per query.

text
     CLIENT (libpq)                                      SERVER
1    PQsendQuery("SELECT * FROM orders")            -->  executes, starts sending
2    PQsetSingleRowMode(conn)  -- must be immediate
3    PQgetResult -> PGRES_SINGLE_TUPLE (row 1)      <--  DataRow
4    PQclear(res); PQgetResult -> row 2             <--  DataRow
5    ...
6    PQgetResult -> PGRES_TUPLES_OK (0 rows)        <--  CommandComplete
7    PQgetResult -> NULL                                 -- must still be called until NULL

Real scenario: language drivers built on libpq (psycopg 3 cursor.stream(), Ruby pg set_single_row_mode, node-postgres via pg-query-stream which uses a server cursor instead) expose this as an iterator.

MechanismMemoryServer resourceRound trips
Normal PQexecWhole resultNone after return1
Single-row / chunkedOne row / one chunkRunning statement + snapshot until finished1 (a continuous stream)
DECLARE + FETCH nOne batchPortal + snapshotN/batch + 2
Extended Execute(max_rows)One batchPortalN/batch
Pipeline modeDepends on result handlingSeveral statements in flightFewer: queries are batched

Fix / how to use it: pick the driver feature that maps to it: psycopg 3 with cur.stream(sql) as ..., pgjdbc setFetchSize(n) with autocommit off, pgx Rows (below), pgx SendBatch (the pipeline analogue).

pgx and database/sql in Go Must-know ​

In plain words: in Go, rows.Next() pulls the next row from the connection; with pgx the rows are read off the wire as you iterate, so memory stays flat if you do not keep them.

Common misunderstanding: "rows.Next() lets me abandon the loop whenever I like." If you leave the loop early without closing rows, the connection stays checked out of the pool and busy. Always defer rows.Close(), and check rows.Err() after the loop, because it distinguishes "ran out of rows" from "the connection broke half way".

Definition: database/sql.Rows is the cursor; Next advances, Scan copies, Err reports the iteration error, Close releases the connection. If you pass a context.Context to QueryContext, cancelling it closes the rows and interrupts the query; the package documentation warns "Drivers that do not support context cancellation will not return until after the query is completed." pgx CopyTo (on pgconn.PgConn) writes a COPY ... TO STDOUT stream to an io.Writer.

text
     GO HANDLER                                   POSTGRESQL
1    rows, _ := db.QueryContext(ctx, sql)   -->   Parse/Bind/Execute (all rows, max_rows=0)
2    for rows.Next() { Scan; write }        <--   DataRow stream, read as needed
3    client slow: socket buffer fills             backend waits (wait_event = ClientWrite)
4    ctx cancelled (client left)            -->   pgx sends CancelRequest, closes rows
5    rows.Err() == context.Canceled               statement aborted, snapshot released

Real scenario: an export endpoint for 10M rows runs behind a load balancer; users close the tab after 20 seconds. Without r.Context() the query keeps running for 10 minutes. With it, the query is cancelled within milliseconds.

Go APIBehaviour
db.Query / QueryContextStreams rows; connection held until Close or exhaustion
rows.Next / Scan / Err / CloseThe loop contract
pgx.Rows (conn.Query)Same, native types, no database/sql overhead
pgx.CollectRowsReads all rows into a slice: the buffered way
conn.PgConn().CopyTo(ctx, w, sql)COPY ... TO STDOUT to an io.Writer
conn.CopyFromThe reverse: bulk load
sql.TxOptions{ReadOnly: true, Isolation: sql.LevelRepeatableRead}One stable snapshot for the export

Fix / how to use it: the "before" and "after" are below. Note go/before is a buffered export that works at 10k rows and fails at 10M.

go
// Before: the whole result set is materialised in memory before the first byte
// is written. 10M rows x ~100 bytes of Go structs is several GB of heap.
package main

import (
	"database/sql"
	"encoding/csv"
	"log"
	"net/http"
	"strconv"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

type order struct {
	ID         int64
	CustomerID int64
	TotalCents int64
	Status     string
	CreatedAt  time.Time
}

func exportHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		rows, err := db.Query(`SELECT id, customer_id, total_cents, status, created_at FROM orders`)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close()

		var all []order // grows without bound
		for rows.Next() {
			var o order
			if err := rows.Scan(&o.ID, &o.CustomerID, &o.TotalCents, &o.Status, &o.CreatedAt); err != nil {
				http.Error(w, err.Error(), http.StatusInternalServerError)
				return
			}
			all = append(all, o)
		}

		w.Header().Set("Content-Type", "text/csv")
		cw := csv.NewWriter(w)
		for _, o := range all {
			_ = cw.Write([]string{strconv.FormatInt(o.ID, 10), o.Status})
		}
		cw.Flush()
	}
}

func main() {
	db, err := sql.Open("pgx", "postgres://app@localhost/shop")
	if err != nil {
		log.Fatal(err)
	}
	http.Handle("/export.csv", exportHandler(db))
	log.Fatal(http.ListenAndServe(":8080", nil))
}
go
// After: stream rows from database/sql to CSV to HTTP chunked, one row at a
// time, and stop work the moment the client disconnects.
package main

import (
	"context"
	"database/sql"
	"encoding/csv"
	"errors"
	"log"
	"net/http"
	"strconv"
	"time"

	_ "github.com/jackc/pgx/v5/stdlib"
)

const flushEvery = 5000 // rows between explicit flushes of the HTTP buffer

func exportHandler(db *sql.DB) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		// r.Context() is cancelled when the client goes away; the timeout is a
		// hard ceiling so an export cannot hold a snapshot forever.
		ctx, cancel := context.WithTimeout(r.Context(), 15*time.Minute)
		defer cancel()

		// Read-only repeatable-read transaction: one stable snapshot for the
		// whole export, and the server knows we will not write.
		tx, err := db.BeginTx(ctx, &sql.TxOptions{Isolation: sql.LevelRepeatableRead, ReadOnly: true})
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer tx.Rollback() // releases the snapshot even on early return

		rows, err := tx.QueryContext(ctx,
			`SELECT id, customer_id, total_cents, status, created_at FROM orders ORDER BY id`)
		if err != nil {
			http.Error(w, err.Error(), http.StatusInternalServerError)
			return
		}
		defer rows.Close() // frees the connection even if we stop early

		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
		w.Header().Set("Content-Disposition", `attachment; filename="orders.csv"`)
		// No Content-Length: Go switches to Transfer-Encoding: chunked (HTTP/1.1).
		flusher, _ := w.(http.Flusher)

		cw := csv.NewWriter(w)
		_ = cw.Write([]string{"id", "customer_id", "total_cents", "status", "created_at"})

		n := 0
		for rows.Next() {
			var (
				id, customer, total int64
				status              string
				created             time.Time
			)
			if err := rows.Scan(&id, &customer, &total, &status, &created); err != nil {
				log.Printf("scan: %v", err)
				return // headers already sent: all we can do is abort the stream
			}
			rec := []string{
				strconv.FormatInt(id, 10), strconv.FormatInt(customer, 10),
				strconv.FormatInt(total, 10), status, created.UTC().Format(time.RFC3339),
			}
			if err := cw.Write(rec); err != nil {
				return // client gone: the deferred Close/Rollback run
			}
			n++
			if n%flushEvery == 0 {
				cw.Flush()
				if flusher != nil {
					flusher.Flush() // backpressure: Write blocks if the client is slow
				}
				if ctx.Err() != nil {
					return
				}
			}
		}
		// rows.Err distinguishes "no more rows" from "stream broke half way".
		if err := rows.Err(); err != nil && !errors.Is(err, context.Canceled) {
			log.Printf("export aborted after %d rows: %v", n, err)
			return // do NOT write a clean ending: the truncated body signals failure
		}
		cw.Flush()
	}
}

func main() {
	db, err := sql.Open("pgx", "postgres://app@localhost/shop")
	if err != nil {
		log.Fatal(err)
	}
	db.SetMaxOpenConns(10)
	http.Handle("/export.csv", exportHandler(db))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

What each database really does ​

MySQL unbuffered queries and "Commands out of sync" Must-know ​

In plain words: MySQL clients download the whole result by default. If you ask for an unbuffered query, rows stream, but the connection is "in use" until you have read every row.

Common misunderstanding: "MySQL has server-side cursors for SELECT." Only inside stored programs, and prepared-statement cursors via the C API / Connector/J useCursorFetch=true. For ordinary PHP and Go code, "streaming" means unbuffered (mysql_use_result) reading.

Definition: the PHP manual: "Queries are using the buffered mode by default. This means that query results are immediately transferred from the MySQL Server to PHP and then are kept in the memory of the PHP process." Unbuffered: "Unless the full result set was fetched from the server no further queries can be sent over the same connection." In PDO set PDO::MYSQL_ATTR_USE_BUFFERED_QUERY to false; in mysqli use MYSQLI_USE_RESULT. Breaking the rule gives MySQL error 2014 CR_COMMANDS_OUT_OF_SYNC, "Commands out of sync; you can't run this command now" (PDO: "Cannot execute queries while other unbuffered queries are active").

text
     PHP (pdo_mysql, buffered = false)
1    $stmt = $pdo->query("SELECT * FROM orders");   -- unbuffered, rows stay on the server
2    $row = $stmt->fetch();                         -- row 1
3    $pdo->query("UPDATE counters SET n = n+1");    -- ERROR 2014: Commands out of sync
4    -- fix: finish the loop (or $stmt->closeCursor()) before the next statement,
5    --      or use a second connection for the UPDATE

Real scenario: a Laravel job iterates with cursor() on an unbuffered connection and calls Model::create() inside the loop on the same connection: the first insert raises error 2014. The fix is to write through a second connection, or to use lazyById (buffered, short queries) instead.

ClientUnbuffered switchGotcha
PHP mysqli$mysqli->query($sql, MYSQLI_USE_RESULT)num_rows unknown until the end
PHP PDOPDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false (PHP 8.4: Pdo\Mysql::ATTR_USE_BUFFERED_QUERY)Error 2014 on a second statement
go-sql-driver/mysqlRows are read from the socket as you iterateIn a Tx, issuing another query while rows are open fails with busy buffer; outside a Tx, database/sql uses another pooled connection
Connector/JsetFetchSize(Integer.MIN_VALUE) streaming, or useCursorFetch=true + fetch sizeSame one-active-result rule
MySQL C APImysql_use_result vs mysql_store_resultServer holds the result and a row-level read view while you read

Fix / how to use it: the PHP code, including the unbuffered switch, is in CursorVsLazy.php (see Laravel).

SQL Server cursor types Good to know ​

In plain words: SQL Server has four cursor flavours that differ in how much of the data is frozen at OPEN.

Common misunderstanding: "A cursor is always slow in SQL Server." FAST_FORWARD (forward-only, read-only, optimised) and the default result set ("firehose") are the cheap streaming paths; STATIC copies into tempdb, KEYSET builds a key table in tempdb, DYNAMIC sees live changes.

Definition (Microsoft's DECLARE CURSOR reference): STATIC "makes a temporary copy of the data" and "doesn't detect changes"; KEYSET: "membership and order of rows ... are fixed when the cursor is opened" but value changes are detected; DYNAMIC reflects all changes; FAST_FORWARD is forward-only read-only. FETCH status is read from @@FETCH_STATUS (0 ok, -1 past the end, -2 row deleted in a keyset cursor).

TypeMembershipValue changesCost
STATICFrozen copy in tempdbNot seenCopy at OPEN
KEYSETKeys frozen in tempdbSeen; deletes show as gaps (-2)Key table
DYNAMICLiveSeenNo copy; may be slower, unstable position
FAST_FORWARDForward-only, read-onlyDefault FORWARD_ONLY cursors are dynamicCheapest

Fix / how to use it: DECLARE c CURSOR LOCAL FAST_FORWARD FOR SELECT id FROM dbo.orders ORDER BY id;, OPEN c;, FETCH NEXT FROM c INTO @id; in a WHILE @@FETCH_STATUS = 0 loop, then CLOSE c; DEALLOCATE c;. With SQL Server's MARS setting a connection may have several active result sets; without it, finish reading first.

Oracle ref cursors, MongoDB cursors, SQLite, Redis Good to know ​

In plain words: every engine has its own version of "give me the next batch"; the vocabulary differs.

Common misunderstanding: "A Redis SCAN cursor is a database cursor." It is a stateless integer token; Redis keeps no server-side iteration state, which is why SCAN may return a key twice and never guarantees a snapshot.

Definition: Oracle has explicit cursors and ref cursors (SYS_REFCURSOR, OPEN cur FOR query) that a PL/SQL function can return to a client; clients fetch in array-size batches (BULK COLLECT ... LIMIT n in PL/SQL, prefetch rows in OCI/JDBC). Oracle's read consistency uses undo, so a cursor open for a long time can hit ORA-01555: snapshot too old instead of holding locks. MongoDB returns a cursor with a batchSize (first batch up to 101 documents, subsequent batches getMore up to 16 MiB), idle cursors time out after 10 minutes unless noCursorTimeout. SQLite has no cursor SQL: sqlite3_step yields one row per call, and the open statement holds a read transaction. CockroachDB supports DECLARE/FETCH over the PostgreSQL wire protocol in recent versions (check your version's docs). Redis SCAN / SSCAN / HSCAN / ZSCAN use a client-held cursor token.

EngineBatch knobWhat can go wrong
OraclePrefetch / array size, BULK COLLECT LIMITORA-01555 on long cursors
MongoDBbatchSize, cursorTimeoutMillisCursorNotFound (error 43) after the idle timeout
SQLiten/a (row at a time)Long reader blocks WAL checkpoint
CockroachDBFETCH nTransaction retries (40001) inside long transactions
RedisSCAN ... COUNT nDuplicates; no snapshot

Cursor stability and updatable cursors ​

Cursor stability and cursor lost update Important ​

In plain words: if you read a row through a cursor and then update "the row I am looking at", someone else may have changed it in between; cursor stability is the old rule "keep the current row locked while the cursor is on it".

Common misunderstanding: "UPDATE ... WHERE CURRENT OF is atomic with the fetch." Only with FOR UPDATE. The manual: "Without FOR UPDATE, a subsequent WHERE CURRENT OF command will have no effect if the row was changed since the cursor was created."

Definition: Berenson et al. name the anomaly P4C, rc1[x]...w2[x]...w1[x]...c1, and the level that prevents it Cursor Stability (see Isolation Levels). In PostgreSQL the practical form is DECLARE c CURSOR FOR SELECT ... FOR UPDATE: rows are locked when first fetched and are the latest committed versions.

text
     T1 (cursor)                                   T2
1    BEGIN;
2    DECLARE c CURSOR FOR SELECT id, qty FROM stock WHERE id=7;      -- no FOR UPDATE
3    FETCH c;                          -- qty=5
4                                      UPDATE stock SET qty=0 WHERE id=7;  COMMIT;
5    UPDATE stock SET qty=qty-1 WHERE CURRENT OF c;   -- "no effect": the row changed
6    -- with FOR UPDATE: step 4 would have WAITED for T1, no lost update

Real scenario: a batch repricing job fetches products through a cursor while merchants edit prices; with FOR UPDATE each row is locked at fetch, so a merchant's edit waits for the job (bounded by batch size) instead of being overwritten.

EngineUpdatable cursorBehaviour
PostgreSQLUPDATE/DELETE ... WHERE CURRENT OF c; FOR UPDATE recommendedNo effect on changed row without FOR UPDATE; cursors "not simply updatable" can fail in production only
MySQLNot supported in stored-program cursors (read-only)Use SELECT ... FOR UPDATE plus keyed updates
SQL ServerUPDATE ... WHERE CURRENT OF; SCROLL_LOCKS/OPTIMISTICOPTIMISTIC detects changes with a version or checksum
OracleSELECT ... FOR UPDATE + WHERE CURRENT OFLocks all selected rows at OPEN

Fix / how to use it: for most jobs skip updatable cursors: read keys by keyset, update with UPDATE ... WHERE id = :id AND version = :v (see Optimistic vs Pessimistic Locking).

Application-level streaming ​

Laravel cursor(), lazy() and lazyById() Must-know ​

In plain words: cursor() runs one query and hands you rows one at a time through a PHP generator. lazy() runs many small queries (pages) and hides that behind one lazy collection. lazyById() does the same with keyset paging by primary key.

Common misunderstanding: "cursor() is a database cursor, so memory is bounded." It is not: it is a generator over PDOStatement::fetch(). The Eloquent builder's cursor() is new LazyCollection(fn () => yield from $this->connection->cursor(...)), and Connection::cursor does prepare, execute, then while ($record = $statement->fetch(...)) { yield $record; }. Models are hydrated one at a time, but the driver has usually already buffered the rows. The Laravel manual: "The cursor method will only execute a single database query; however, the individual Eloquent models will not be hydrated until they are actually iterated over", and "it will still eventually run out of memory. This is due to PHP's PDO driver internally caching all raw query results in its buffer. ... consider using the lazy method instead."

Definition:

MethodQueriesServer cursor?MemorySafe to update iterated rows?Eager loading
get() / all()1NoWhole result as modelsn/aYes
chunk(n)N/n, OFFSET pagesNoOne chunkNo: updating the filter column skips rowsYes
chunkById(n)N/n, keyset (id > last)NoOne chunkYesYes
lazy(n)N/n, OFFSET pagesNoOne chunkNo (same as chunk)Yes
lazyById(n)N/n, keysetNoOne chunkYesYes
cursor()1No (a PDO statement + generator)Driver buffer + one modeln/aNo
cursorPaginate()1 per pageNoOne pagen/aYes: this is keyset pagination, unrelated to cursor()
text
     lazyById(1000) in Laravel 13                       DATABASE
1    SELECT ... WHERE id > 0     ORDER BY id LIMIT 1000  -->  chunk 1 (own short autocommit statement)
2    yield row 1 ... row 1000 (one model at a time)
3    SELECT ... WHERE id > 1000  ORDER BY id LIMIT 1000  -->  chunk 2 (fresh snapshot, nothing held between)
4    ...
5    last chunk has < 1000 rows -> generator ends

Real scenario: an orders:export command used Order::all()->each(...) (works at 50k rows, OOM at 5M). Moving to lazyById(2000) bounds memory at about one chunk of models and holds no transaction between chunks. Because lazyById adds WHERE id > :last ORDER BY id, it is also correct when the loop flips status, while lazy() with OFFSET would silently skip rows.

ConditionChoose
Read-only, MySQL, you can set the PDO attribute to unbufferedcursor() genuinely streams, but no second query on the same connection
Read-only, PostgreSQL (pdo_pgsql)lazyById; cursor() still materialises the result inside libpq
Loop updates a column used in the filterlazyById / chunkById
Need eager loading (with())lazy/lazyById, not cursor()
Need a real server cursorRaw DECLARE/FETCH in a transaction (pgServerCursor())

Fix / how to use it: the "before" and the streamed lazyById export:

php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Illuminate\Http\Response;

class OrderExportController
{
    // Before: get() builds a Collection of 10M Eloquent models, then the response
    // body is built in memory as one string. Peak memory is several GB.
    public function __invoke(): Response
    {
        $csv = "id,customer_id,total_cents,status\n";

        foreach (Order::query()->get() as $order) {
            $csv .= "{$order->id},{$order->customer_id},{$order->total_cents},{$order->status}\n";
        }

        return new Response($csv, 200, ['Content-Type' => 'text/csv']);
    }
}
php
<?php

namespace App\Http\Controllers;

use App\Models\Order;
use Symfony\Component\HttpFoundation\StreamedResponse;

class OrderExportController
{
    // After: lazyById() runs one short keyset query per chunk (WHERE id > :last
    // ORDER BY id LIMIT 2000), yields models one by one, and the response is
    // streamed with chunked transfer encoding. Memory stays flat.
    public function __invoke(): StreamedResponse
    {
        return response()->streamDownload(function () {
            $out = fopen('php://output', 'w');
            fputcsv($out, ['id', 'customer_id', 'total_cents', 'status', 'created_at']);

            $sent = 0;

            // select() only the columns you export: hydration cost is per column.
            $orders = Order::query()
                ->select(['id', 'customer_id', 'total_cents', 'status', 'created_at'])
                ->lazyById(2000, column: 'id');

            foreach ($orders as $order) {
                fputcsv($out, [
                    $order->id,
                    $order->customer_id,
                    $order->total_cents,
                    $order->status,
                    $order->created_at?->toIso8601String(),
                ]);

                if (++$sent % 5000 === 0) {
                    fflush($out);
                    flush(); // push the chunk to the client (backpressure: blocks if it is slow)

                    if (connection_aborted()) {
                        return; // client left: stop querying
                    }
                }
            }

            fclose($out);
        }, 'orders.csv', [
            'Content-Type' => 'text/csv; charset=utf-8',
            'X-Accel-Buffering' => 'no', // nginx: do not buffer the whole body
        ]);
    }
}
php
<?php

namespace App\Services;

use App\Models\Order;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\LazyCollection;
use PDO;

class CursorVsLazy
{
    // cursor(): ONE statement, a PHP generator over PDOStatement::fetch().
    // Saves model hydration memory, but on pdo_mysql (buffered by default) and
    // pdo_pgsql the driver has already pulled the whole result into the process.
    public function viaCursor(): int
    {
        $sum = 0;
        foreach (Order::query()->where('status', 'paid')->cursor() as $order) {
            $sum += $order->total_cents;
        }

        return $sum;
    }

    // lazy(): many queries, each LIMIT/OFFSET by page (chunk()-style), models
    // yielded one at a time. Driver memory is bounded by the chunk size.
    // Unsafe if the loop changes the column used in the WHERE clause or the order.
    public function viaLazy(): int
    {
        return Order::query()->where('status', 'paid')->lazy(1000)->sum('total_cents');
    }

    // lazyById(): many queries, keyset by primary key (WHERE id > :last).
    // Safe when you update rows you are iterating; no OFFSET skipping cost.
    public function viaLazyById(): int
    {
        $sum = 0;
        Order::query()->where('status', 'paid')->lazyById(1000)->each(function (Order $order) use (&$sum) {
            $sum += $order->total_cents;
        });

        return $sum;
    }

    // MySQL only: make cursor() genuinely unbuffered. Rules: read ALL rows (or
    // free the statement) before issuing another query on the SAME connection,
    // otherwise MySQL answers "Commands out of sync" (SQLSTATE 2014).
    public function unbufferedMysql(): LazyCollection
    {
        DB::connection('mysql')->getPdo()->setAttribute(PDO::MYSQL_ATTR_USE_BUFFERED_QUERY, false);

        return DB::connection('mysql')->table('orders')->select(['id', 'total_cents'])->cursor();
    }

    // PostgreSQL: a real server-side cursor through plain SQL inside a transaction.
    public function pgServerCursor(): \Generator
    {
        DB::beginTransaction();
        try {
            DB::statement('DECLARE c NO SCROLL CURSOR FOR SELECT id, total_cents FROM orders ORDER BY id');

            do {
                $batch = DB::select('FETCH FORWARD 2000 FROM c');
                yield from $batch;
            } while (count($batch) === 2000);

            DB::statement('CLOSE c');
        } finally {
            DB::rollBack(); // read-only work: nothing to commit, and the snapshot is released
        }
    }
}

Go rows.Next(), context cancellation and pgx CopyTo Must-know ​

In plain words: your loop controls the pace; the context controls when to give up.

Common misunderstanding: "If the HTTP client disconnects, my loop stops by itself." The loop ends only if a Write fails or the context-bound query is cancelled. A handler that ignores r.Context() keeps the query, its connection and its snapshot alive.

Definition: http.Request.Context() is cancelled when the client connection closes or the handler returns; passing it to QueryContext ties the database statement to the client. pgx then sends a PostgreSQL CancelRequest on a separate connection and rows.Err() reports context canceled.

text
     CLIENT              GO HANDLER                          POSTGRESQL
1    GET /export.csv --> BeginTx(ctx, ReadOnly)          -->  snapshot S
2                        QueryContext(ctx, SELECT ...)   -->  statement running
3                        Write/Flush rows <------------------ rows streaming
4    (closes tab)        r.Context() cancelled
5                        pgx: CancelRequest              -->  "canceling statement due to user request" (57014)
6                        rows.Err()=context.Canceled; defer Rollback releases snapshot S

Real scenario: a SaaS lets customers export their audit log; 12% of exports are abandoned. Context cancellation turns 12% of wasted 4-minute scans into immediate cancellations.

ConcernGo mechanism
Stop on client disconnectQueryContext(r.Context(), ...)
Hard time limitcontext.WithTimeout
Slow clientWrite blocks; backpressure flows to PostgreSQL (ClientWrite)
Detect failure mid-streamrows.Err(); return without writing a clean end
Free the connectiondefer rows.Close(), defer tx.Rollback()
Bypass row objectsPgConn().CopyTo(ctx, w, "COPY ... TO STDOUT")

Fix / how to use it: the COPY variant, which moves bytes only:

go
// COPY ... TO STDOUT streamed straight into the HTTP response with pgx.
// The server formats CSV itself; Go only moves bytes.
package main

import (
	"context"
	"log"
	"net/http"
	"os"

	"github.com/jackc/pgx/v5/pgxpool"
)

func exportHandler(pool *pgxpool.Pool) http.HandlerFunc {
	return func(w http.ResponseWriter, r *http.Request) {
		conn, err := pool.Acquire(r.Context())
		if err != nil {
			http.Error(w, err.Error(), http.StatusServiceUnavailable)
			return
		}
		defer conn.Release()

		w.Header().Set("Content-Type", "text/csv; charset=utf-8")
		w.Header().Set("Content-Disposition", `attachment; filename="orders.csv"`)

		// CopyTo writes every CopyData message from the server to w as it arrives.
		// If the client disconnects, w.Write fails and CopyTo returns the error.
		tag, err := conn.Conn().PgConn().CopyTo(r.Context(), w,
			`COPY (SELECT id, customer_id, total_cents, status, created_at
			         FROM orders ORDER BY id)
			 TO STDOUT WITH (FORMAT csv, HEADER true)`)
		if err != nil {
			log.Printf("copy aborted: %v", err) // body is already truncated
			return
		}
		log.Printf("exported %d rows", tag.RowsAffected())
	}
}

func main() {
	pool, err := pgxpool.New(context.Background(), os.Getenv("DATABASE_URL"))
	if err != nil {
		log.Fatal(err)
	}
	defer pool.Close()
	http.Handle("/export.csv", exportHandler(pool))
	log.Fatal(http.ListenAndServe(":8080", nil))
}

Solving the classic problem: streaming exports ​

COPY vs SELECT for bulk export Must-know ​

In plain words: COPY is PostgreSQL's bulk pipe: one command, the server formats rows as CSV or binary and streams them with almost no per-row protocol overhead.

Common misunderstanding: "COPY ... TO writes a file on my laptop." COPY ... TO 'path' writes on the server and needs superuser or pg_write_server_files. To receive the data in the client use COPY ... TO STDOUT (or psql's \copy, which wraps it).

Definition: COPY (SELECT ...) TO STDOUT WITH (FORMAT csv, HEADER true) (the COPY TO STDOUT form); formats text, csv, binary. The result arrives as CopyData messages, which pgx CopyTo and libpq PQgetCopyData read. pg_dump uses COPY by default (it switches to INSERT only with --inserts/--column-inserts) inside a single REPEATABLE READ snapshot-isolated transaction, and parallel dumps (-j) synchronise workers with an exported snapshot; that snapshot is the same long-transaction cost described above.

text
     SELECT path                                    COPY path
1    server: row -> RowDescription + DataRow        server: row -> text/CSV line
2    client: parse each field into a Go/PHP value   client: receive CopyData bytes
3    client: re-encode as CSV and write             client: write bytes straight to the socket/file
4    per-row allocations, per-field conversions     no per-row objects

Real scenario: a 10M-row export that takes 6 minutes with a Go rows.Scan loop and CSV encoding is typically several times faster with COPY (an expected shape, not a promise; measure on your own data with the lab), because the server does the formatting and Go only copies bytes.

AspectCOPY ... TO STDOUTStreaming SELECT + app CSV
ThroughputHighestLower (per-row parse and encode)
Row transformation in app codeNone (do it in SQL)Anything
Formattext / csv / binaryAnything
MemoryConstantConstant if streamed
Progress / row countCommand tag at the endCounted as you go
Works with views, joinsCOPY (SELECT ...) yesYes
Other enginesMySQL SELECT ... INTO OUTFILE (server side), mysqldump; SQL Server bcp; Oracle SQL*Plus spool / Data PumpAny driver

Fix / how to use it:

sql
\copy (SELECT id, customer_id, total_cents, status, created_at FROM orders ORDER BY id) TO 'orders.csv' WITH (FORMAT csv, HEADER true)
-- server-side equivalent, writes on the DB host: COPY (...) TO '/var/lib/postgresql/orders.csv' ...

CSV, S3 and HTTP exports with backpressure Important ​

In plain words: a streaming export is a pipe: database to your process to the destination. The slowest stage sets the speed, and every stage must refuse to buffer without limit.

Common misunderstanding: "Streaming means the first byte arrives instantly." Only if nothing in the path buffers: PHP output buffering, a gzip middleware, nginx proxy_buffering/fastcgi_buffering (set X-Accel-Buffering: no), or a CDN. And an HTTP error status cannot be sent after the first byte.

Definition: HTTP/1.1 sends a body without Content-Length using Transfer-Encoding: chunked (HTTP/2 uses DATA frames). NDJSON (application/x-ndjson) is one JSON object per line, so clients can parse incrementally. Backpressure is the property that a slow reader slows the writer: a blocked Write stops the rows.Next() loop, which stops reading the socket, which fills the TCP window, which makes PostgreSQL wait on ClientWrite. S3 uploads use multipart upload (parts of at least 5 MiB except the last, up to 10,000 parts), so the uploader reads from an io.Pipe fed by COPY.

text
     DB  -->  COPY / rows.Next  -->  gzip  -->  io.Pipe  -->  S3 multipart parts (8 MiB each)
1    each stage blocks when its output is full (bounded buffers)
2    S3 part upload fails -> pipe writer gets an error -> COPY is cancelled -> snapshot released
3    success -> CompleteMultipartUpload; failure -> AbortMultipartUpload (or lifecycle rule)

Real scenario:

  • "Download CSV" button for 2M rows: streamed lazyById response, Content-Disposition: attachment, no temp file.
  • Nightly warehouse feed: a job runs COPY into gzip into S3, then publishes an event with the object key (microservice style).
  • A public API returns NDJSON; the last line is {"type":"end","rows":1832044} so clients can tell a complete stream from a truncated one.
DestinationMechanismBackpressureFailure signal
HTTP downloadChunked response, Flush every N rowsBlocking writeTruncated body / reset; no status change
NDJSON APIOne JSON per line, final end recordBlocking writeMissing end record
File on diskbufio.Writer / fputcsvDisk speedExit code
S3Multipart upload from io.PipePart upload speedAbortMultipartUpload
Message queueBatch to producerProducer Send blocksRedelivery

Fix / how to use it: the Go and Laravel handlers above already flush every 5000 rows, bound memory and stop on disconnect. For Laravel the response is a StreamedResponse (response()->streamDownload).

Keyset vs cursor ​

In plain words: keyset pagination remembers the last key you saw in the client; a cursor remembers it on the server.

Common misunderstanding: "A cursor replaces pagination." A cursor gives a single consistent pass; it is useless for a UI where users return tomorrow, because it dies with the transaction. Keyset works across requests, restarts and servers. Offset vs keyset is in Pagination.

AspectServer-side cursorKeyset (WHERE id > :last LIMIT n)OFFSET
StateOn the server (portal)In the clientNone
Survives restart/reconnectNo (WITH HOLD: only session)YesYes
ConsistencyOne snapshot for the whole passEach chunk its own snapshot (rows may appear/disappear between chunks)Per query, may skip/duplicate
Holds a transactionYesNoNo
Cost per chunkConstantConstant with an indexGrows with offset
Jump to page NFETCH ABSOLUTE (walks rows)NoYes, but slow
Best forOne-pass exports needing a consistent snapshotLong jobs, resumable jobs, APIsSmall tables, shallow pages

Fix / how to use it: resumable job: persist the last processed key (jobs.checkpoint = 2_345_000), restart from there. SQL: SELECT * FROM orders WHERE id > $1 ORDER BY id LIMIT 2000.

Failure handling while streaming ​

In plain words: once you have sent the first byte you cannot change your mind; a broken stream must look broken.

FailureWhat you seeWhat to do
Client disconnectsWrite error / cancelled contextStop the query; roll back
Database connection drops mid-streamrows.Err(), SQLSTATE 08006/57P01 (admin shutdown)Abort the response (do not end cleanly); caller retries the export
idle_in_transaction_session_timeout fires25P03 on the next FETCHReduce work between batches
statement_timeout57014 canceling statement due to statement timeoutRaise it for the export role only
Replica query conflictSQLSTATE 40001, canceling statement due to conflict with recoveryUse max_standby_streaming_delay, a dedicated replica
MySQL Commands out of syncerror 2014Do not run a second statement on the same connection
Serialization failure (SERIALIZABLE, CockroachDB)40001Whole export restarts

Rule list: (1) never wrap an HTTP stream in a retry that restarts silently after bytes were sent; (2) make exports idempotent and resumable (keyset checkpoint, object key per attempt); (3) use a final marker (row count, NDJSON end record, or a .done object in S3); (4) cap duration with timeouts; (5) alert on exports whose transaction age exceeds a threshold.

Choosing ​

Result may be large?Human clicking pages?keyset paginationExport file / stream?COPY TO STDOUT firstPer-row app logic?stream or cursorLong tx OK?yes: one streamNo: chunkedkeyset / lazyByIdWhatever you choose: bound memory, bound time (statement/idle timeouts), honour cancellation.
WorkloadRecommended techniqueExtraReason
UI list with "next page"Keyset paginationOpaque token (cursorPaginate)Stateless, constant cost
"Download CSV" for 10k–1M rowsStreaming SELECT or lazyById to chunked responseset_time_limit, no buffering proxyBounded memory, first byte early
Export 10M+ rowsCOPY ... TO STDOUT to S3/HTTP via pipeRead replica, timeoutsHighest throughput, constant memory
Batch job, per-row logic, no updates to sourceDECLARE/FETCH FORWARD n or streaming Rowscursor_tuple_fraction = 1.0One snapshot, bounded memory
Batch job that updates what it readslazyById / chunkById / keysetCommit per chunkNo long transaction
Job must survive commitsWITH HOLD or keyset checkpointCLOSE explicitlyCursor outlives transaction
Behind PgBouncer transaction poolingKeyset chunksDedicated session-mode connection for exportsPortals do not cross transactions
MySQL, memory-critical readUnbuffered query on a dedicated connectionNo second query on itRows stay on the server
SQL Server batch loopLOCAL FAST_FORWARD cursor, or set-based SQLPrefer set-basedCheapest cursor

In architecture: from a single process to a distributed system ​

Monolith (one process, one database) ​

A Laravel monolith with MySQL and a "Download orders" button. The simplest correct design: lazyById(2000) into streamDownload, select() only the exported columns, a read-only database user, set_time_limit(0) only on that route, and X-Accel-Buffering: no. A Go monolith does the same with QueryContext(r.Context()) and chunked CSV. Example flow: browser, nginx (no buffering), PHP-FPM worker, one chunk query every 2000 rows. Worker count matters: each streaming export occupies a PHP-FPM worker for minutes, so cap concurrent exports (a semaphore or a queue) before they starve ordinary requests.

Modular monolith / multiple databases ​

Modules own their schemas; an "export" module reads other modules' data through their public query interfaces, not their tables. Cursors do not cross databases: a join across two databases is a nested loop in application code, so stream the larger side and look up the smaller side with a batch WHERE id IN (...). Example: Reporting streams invoices (billing DB) in lazyById chunks, enriches each chunk with one customers lookup (CRM DB) per chunk.

Microservices ​

A synchronous 10-minute HTTP export through three services is fragile. Use the asynchronous pattern: POST /exports returns 202 with a job id; a worker streams COPY into gzip into S3; on completion it publishes export.completed {id, key, rows} (via outbox); the client polls or receives a webhook with a pre-signed URL. Failure semantics: the worker's checkpoint is the S3 multipart upload id plus the last key; a redelivered message must not start a second export for the same job id (idempotency key). Service-to-service reads of large collections should stream NDJSON with the end-record convention, with the consumer applying backpressure.

Distributed data (replicas, caches, sharded SQL) ​

Run exports on a read replica so they cannot pin the primary's cleanup horizon, but know the replica's own rules: a long query on a hot standby can be cancelled with canceling statement due to conflict with recovery unless max_standby_streaming_delay is raised, while hot_standby_feedback = on makes the primary keep old rows (bloat returns, see Replication & Failover). Replica lag means the export is a point-in-time view that may be seconds old. Behind PgBouncer in transaction mode, DECLARE + FETCH in separate transactions break because server connections are swapped between transactions; use session mode for exports (Connection Pooling). For sharded or distributed SQL (CockroachDB, Citus), a cursor spans nodes and long transactions face 40001 retries; prefer keyset chunks per shard with a merge in the client, or an offline path: logical decoding or CDC into object storage.

Scaling path ​

ScaleRows per exportTechnique
1x< 100kget() / rows into a slice is fine
10x~1MStreaming lazyById / rows.Next, chunked response
100x~10M–100MCOPY to S3 from a replica, async job, resumable keyset
1000xbillionsPartition-wise parallel COPY, CDC to a lake (Parquet), no live-database exports; see Billion-Row Tables

Lab ​

Setup (PostgreSQL 16+; use a scratch database):

sql
CREATE TABLE orders (
  id bigserial PRIMARY KEY, customer_id bigint NOT NULL, total_cents bigint NOT NULL,
  status text NOT NULL, created_at timestamptz NOT NULL DEFAULT now());
INSERT INTO orders (customer_id, total_cents, status)
SELECT (random()*100000)::bigint, (random()*50000)::bigint, (ARRAY['new','paid','shipped'])[1 + (random()*2)::int]
FROM generate_series(1, 10000000);
ANALYZE orders;

Lab 1: DECLARE/FETCH in two terminals, locks and snapshot ​

text
     TERMINAL A                                         TERMINAL B
1    BEGIN;
2    DECLARE c NO SCROLL CURSOR FOR
       SELECT id FROM orders ORDER BY id;
3    FETCH 5 FROM c;                                    -- ids 1..5
4                                                       UPDATE orders SET status='x' WHERE id=3;
5                                                       SELECT state, backend_xmin, xact_start
                                                          FROM pg_stat_activity WHERE pid <> pg_backend_pid();
                                                        -- expect: A is 'idle in transaction', backend_xmin set
6                                                       SELECT locktype, relation::regclass, mode
                                                          FROM pg_locks WHERE pid = <A's pid>;
                                                        -- expect: AccessShareLock on orders and orders_pkey
7                                                       ALTER TABLE orders ADD COLUMN lab int;  -- blocks!
8                                                       -- in a third terminal: SELECT 1 FROM orders LIMIT 1;  -- also blocks (queue)
9    FETCH 5 FROM c;                                    -- row 3 still shows its OLD status (snapshot)
10   COMMIT;                                            -- B's ALTER proceeds, queued SELECT proceeds
11                                                      VACUUM (VERBOSE) orders;  -- run while A is open: "dead but not yet removable"

Lab 2: memory, buffered vs unbuffered (describe and measure) ​

  1. psql: \set FETCH_COUNT 0 then \o /dev/null and SELECT * FROM orders; under /usr/bin/time -l psql ... (macOS) or /usr/bin/time -v (Linux); note "maximum resident set size". Expect gigabytes, because psql buffers the whole PGresult.
  2. Repeat with \set FETCH_COUNT 10000. psql now runs the query through a cursor and fetches 10 000 rows at a time; expect a flat, small resident set (tens of MB) and a slightly longer total time.
  3. PHP: run the same table through pdo_mysql twice, printing memory_get_peak_usage(true) after the loop: once with default buffering, once with PDO::MYSQL_ATTR_USE_BUFFERED_QUERY => false; then with lazyById(2000). Expect: buffered and Laravel cursor() similar and large; unbuffered and lazyById flat.
  4. Go: log runtime.ReadMemStats (HeapAlloc) every 100k rows for go/before (grows linearly) and go/export (flat).

Lab 3: export 10M rows with COPY vs a cursor ​

text
     STEP                                                           EXPECTED SHAPE
1    time psql -c "\copy (SELECT * FROM orders ORDER BY id) TO '/tmp/o1.csv' CSV"
                                                                     fastest; server does the formatting
2    time go run ./copyto  (curl -o /tmp/o2.csv localhost:8080/export.csv)
                                                                     close to step 1 (adds HTTP)
3    time curl -o /tmp/o3.csv localhost:8080/export.csv   (go/export, Rows loop)
                                                                     slower: per-row Scan + CSV encode
4    go run ./cursor  (FETCH FORWARD 2000 loop)                      similar to step 3; N/2000 round trips
5    SET cursor_tuple_fraction = 1.0 before DECLARE; repeat step 4   may change the plan on joins
6    kill curl mid-download; check pg_stat_activity                  query gone within a second (cancelled)

Verify with cmp /tmp/o1.csv /tmp/o2.csv (same bytes if the ORDER BY is the same and the format options match). The ordering of results is "typically COPY is several times faster than the row loop", not a promise: record your own numbers.

Common misconceptions ​

BeliefReality
"foreach ($pdo->query(...)) streams"pdo_mysql buffers by default; the whole result is in PHP memory first
"Laravel cursor() uses a database cursor"It is one statement and a PHP generator over PDOStatement::fetch()
"cursor() makes memory constant"Only model hydration is lazy; the PDO buffer still holds all raw rows (Laravel docs say so)
"lazy() and lazyById() are the same"lazy uses OFFSET pages (skips rows if you change the filter column); lazyById is keyset
"cursorPaginate() is a database cursor"It is keyset pagination with an opaque token
"A cursor releases locks at CLOSE"Locks and the snapshot live until COMMIT/ROLLBACK
"WITH HOLD is free"COMMIT copies the remaining rows to temp storage
"Single-row mode is a server cursor"The statement still runs; the snapshot is held until the last row
"A slow consumer only hurts itself"It pins a snapshot (bloat), locks (blocked DDL) and a connection
"MySQL SELECTs can use cursors"Only stored programs and prepared-statement cursors; otherwise unbuffered reading
"Closing the browser tab stops the query"Only if the handler ties the query to the request context
"COPY TO writes to my machine"COPY TO 'file' writes on the server; use STDOUT or \copy

Self-check: questions & answers ​

Show:
  • Must-know asked in almost every interview
  • Important frequent; expected at senior level
  • Good to know extra depth that sets you apart

1 — Why does a foreach over a PDO MySQL result not save memory by default? Must-know ​

Answer

Answer: PDO's default is a buffered query: the whole result is copied into PHP memory before the first iteration. Set PDO::MYSQL_ATTR_USE_BUFFERED_QUERY to false (and accept one-active-result rules) or use chunked keyset queries.

2 — What is the difference between DECLARE ... WITH HOLD and WITHOUT HOLD? Good to know ​

Answer

Answer: WITHOUT HOLD (default) dies at the end of the transaction. WITH HOLD survives COMMIT because PostgreSQL copies the remaining rows to temp storage; it lives until CLOSE or session end and cannot be combined with FOR UPDATE.

3 — What does an idle cursor loop cost the database? Important ​

Answer

Answer: An open transaction: a snapshot (pins backend_xmin, so vacuum cannot clean, causing bloat), ACCESS SHARE locks (queue migrations), and a connection. idle_in_transaction_session_timeout limits it.

4 — How does Laravel cursor() differ from lazyById()? Must-know ​

Answer

Answer: cursor() runs one query and yields models via a generator over PDOStatement::fetch(); the driver may have buffered everything. lazyById() runs many WHERE id > :last ORDER BY id LIMIT n queries, so memory is one chunk and no transaction is held between chunks.

5 — Why does cursor_tuple_fraction matter for exports? Good to know ​

Answer

Answer: The default 0.1 biases the planner toward fast-start plans for cursors; for a job that reads all rows, 1.0 gives the plan a normal query would get.

6 — What is "Commands out of sync" and how do you avoid it? Important ​

Answer

Answer: MySQL error 2014: you issued a statement while an unbuffered result was still being read on the same connection. Read to the end, close the cursor, or use a second connection.

7 — Why pass r.Context() into QueryContext in an export handler? Must-know ​

Answer

Answer: So a disconnected client cancels the query, which releases the connection, snapshot and locks instead of letting the scan run to completion.

8 — When is COPY better than streaming SELECT? Important ​

Answer

Answer: For raw bulk export without per-row application logic: the server formats the rows and the client moves bytes, so throughput is highest and memory constant.

9 — What is backpressure in a streaming export? Must-know ​

Answer

Answer: A slow reader blocks the writer through bounded buffers: blocked Write, full TCP window, PostgreSQL waits on ClientWrite. Nothing accumulates in memory.

10 — How do you tell a complete NDJSON stream from a truncated one? Important ​

Answer

Answer: HTTP status cannot change after the first byte, so end the stream with an explicit record such as {"type":"end","rows":N}; a missing end record means failure.

11 — Why does PgBouncer transaction pooling break cursors? Important ​

Answer

Answer: Server connections are swapped between transactions, so a portal declared in one transaction (or WITH HOLD) may not exist on the connection used for the next.

Cheat sheet ​

TopicWhat to remember
Default driver behaviourBuffers the whole result; streaming is opt-in
Server-side cursorDECLARE c NO SCROLL CURSOR FOR ...; FETCH FORWARD 2000 FROM c; CLOSE c; inside a transaction
WITH HOLDSurvives COMMIT, copies rows to temp storage, cannot be used with FOR UPDATE, CLOSE it
Open cursor costOpen transaction: snapshot (bloat), ACCESS SHARE (blocks DDL), a connection
Timeoutsidle_in_transaction_session_timeout, statement_timeout, lock_timeout on migrations
PlannerSET cursor_tuple_fraction = 1.0 for full-read jobs
MySQLBuffered by default; unbuffered = one active result per connection; error 2014 otherwise
LaravellazyById(n) for safe streaming; cursor() is a generator over one buffered statement
GoQueryContext(r.Context()), defer rows.Close(), check rows.Err(), flush every N rows
Bulk exportCOPY (SELECT ...) TO STDOUT WITH (FORMAT csv); pgx PgConn().CopyTo
HTTPChunked transfer, NDJSON with an end record, disable proxy buffering
PgBouncerTransaction pooling breaks portals across transactions; use session mode for exports
Keyset vs cursorKeyset is stateless and resumable; cursor is one consistent pass

Glossary ​

TermMeaning
CursorA handle to a query's current position from which rows are fetched incrementally
Client-side cursorIteration over rows already downloaded into the driver
Server-side cursorA server object producing rows on demand (portal, SQL Server API cursor, Oracle open cursor)
Result set bufferingDriver storing the whole result before returning it
PortalPostgreSQL's server-side execution state for a statement or cursor
DECLARESQL command creating a cursor
FETCHReads rows from a cursor and moves it
MOVEMoves a cursor without returning rows
CLOSEDestroys a cursor
WITH HOLDCursor survives COMMIT via a temp copy
WITHOUT HOLDCursor ends with its transaction (default)
SCROLL / NO SCROLLWhether backward and absolute fetches are allowed
FETCH FORWARD nFetch the next n rows
Insensitive cursorDoes not see changes made after DECLARE; all PostgreSQL cursors
Cursor stabilityHolding a lock on the cursor's current row; prevents P4C
Cursor lost update (P4C)Lost update through a cursor's current row
WHERE CURRENT OFUpdate or delete the row a cursor is positioned on
cursor_tuple_fractionPlanner estimate of the fraction of cursor rows read (default 0.1)
Single-row modelibpq mode returning one row per result as received
Chunked rows modelibpq mode returning up to n rows per result
Pipeline modelibpq mode sending several queries without waiting for results
Fetch size / batch sizeRows per round trip
Idle in transactionSession with an open transaction running no statement
idle_in_transaction_session_timeoutTerminates sessions idle in a transaction too long
backend_xminOldest snapshot horizon of a session, in pg_stat_activity
BloatDead tuples that cannot be reclaimed or reused
ClientWriteWait event: backend blocked sending to a slow client
BackpressureSlow consumer slows producer instead of filling memory
Unbuffered queryMySQL use_result: rows stay on the server until fetched
Commands out of syncMySQL error 2014; second statement while unbuffered rows pending
lazy()Laravel chunked offset pages as a lazy collection
lazyById()Laravel keyset chunks as a lazy collection
cursor()Laravel single query yielded by a PHP generator
cursorPaginate()Laravel keyset pagination
COPY (query) TO STDOUTPostgreSQL bulk export stream to the client
NDJSONNewline-delimited JSON, one object per line
Chunked transfer encodingHTTP/1.1 body sent without Content-Length
Multipart uploadS3 upload in parts of at least 5 MiB
Ref cursorOracle cursor variable returned to clients
FAST_FORWARDSQL Server forward-only read-only optimised cursor
MARSSQL Server Multiple Active Result Sets

References ​

Built by Morteza Negahi