Cursor lifetime and set-based alternatives
Overview
A cursor lets a client or procedural routine consume query results incrementally. PostgreSQL SQL cursors use DECLARE, FETCH and CLOSE; PL/pgSQL also supports refcursor variables and OPEN. Normal PostgreSQL cursors end with the transaction; WITH HOLD can survive a successful commit in the same session, not rollback of creation. SQLite Python cursors are client API objects, not PostgreSQL server cursors.
First example
SELECT id,qty FROM pc_item ORDER BY id;Observed SQLite result (rows in JSON):
[ [ 1, 10 ], [ 2, 4 ], [ 3, 0 ]]How it works
The first query reads the three rows in stable ID order. The second performs a set-based SUM instead of adding quantities in a loop. The Python lab fetches two rows at a time, then closes the cursor; fetch after close fails. The native PostgreSQL schedule declares a non-scroll cursor, fetches two then one row, and closes before commit. SCROLL allows backward movement where supported; avoid assuming all queries support it. WITH HOLD can materialize rows and consume resources. Cursor iteration can be useful for bounded memory, streaming, or per-row external work, but does not guarantee low server memory or fast execution. Keep transactions short and do not retain unused cursors. Cursor-based pagination by keys is different from an open server cursor.
Practical example
SELECT COALESCE(SUM(qty),0) FROM pc_item;Observed SQLite result (rows in JSON):
[ [ 14 ]]Practice and mistakes
Practice: fetch one row per batch and compare the accumulated sum with SUM(qty). Hint 1: order by id and stop at an empty batch. Hint 2: close in a finally block. Both totals should be 14.
PostgreSQL 17 example — NOT RUN
BEGIN;DECLARE pc_rows NO SCROLL CURSOR FOR SELECT id,qty FROM pc_item ORDER BY id;FETCH FORWARD 2 FROM pc_rows;FETCH FORWARD 2 FROM pc_rows;FETCH FORWARD 2 FROM pc_rows;CLOSE pc_rows;COMMIT;Expected result, not executed: {"fetches": [[[1, 10], [2, 4]], [[3, 0]], []]}