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.

SqlData Fetching

Code

snippet
-- 服务端游标:结果留在服务端,客户端按批取数,不必一次拉全量
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

FAQ

Which tables appear in this script?
`users`, `scan_cursor`, `orders`, `hold_cursor`.