Cursor FETCH Batches Large Results
Keep large result sets on the server and pull them batch by batch with DECLARE CURSOR, FETCH n, and CLOSE, or let WITH HOLD survive the transaction commit.
Code
-- 服务端游标:结果留在服务端,客户端按批取数,不必一次拉全量
BEGIN;
DECLARE scan_cursor NO SCROLL CURSOR FOR
SELECT id, email FROM users ORDER BY id;
-- 每次取一批;取到 0 行说明读完
FETCH 100 FROM scan_cursor;
FETCH 100 FROM scan_cursor;
CLOSE scan_cursor;
COMMIT;
-- WITH HOLD 游标在提交事务后仍可继续读取
BEGIN;
DECLARE hold_cursor NO SCROLL CURSOR WITH HOLD FOR
SELECT id FROM orders WHERE total_cents > 10000;
COMMIT;
FETCH 50 FROM hold_cursor;
CLOSE hold_cursor;Inside the snippet
Several statements share this file — SELECT, with users, scan_cursor, orders and hold_cursor among the objects involved.
Mechanically, the statements are built from: a WHERE clause narrowing which rows one statement affects; an ORDER BY that fixes the output order.
Using it
Run it in the users database context.
Key statements
DECLARE hold_cursor NO SCROLL CURSOR WITH HOLD FOR
SELECT id FROM orders WHERE total_cents > 10000;
DECLARE scan_cursor NO SCROLL CURSOR FOR
SELECT id, email FROM users ORDER BY id;
FETCH 100 FROM scan_cursor;
Interactive Tools for This Topic
SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.cURL to fetch ConverterTranslate a curl command into equivalent JavaScript fetch() code, handling the request method, headers, JSON or raw body, and basic auth.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Which tables appear in this script?
- `users`, `scan_cursor`, `orders`, `hold_cursor`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.