// SQL snippet

Keyset (seek) pagination

Seek past the rows you already have. Page 1000 costs the same as page 1.

Main statement
PostgreSQL
同時涵蓋
SQL Server MySQL SQLite Oracle

The task

You are paging through millions of orders newest-first and need every page to be fast and stable.

The snippet

Written for PostgreSQL. Versions for SQL Server, MySQL, SQLite and Oracle are under Variations.

PostgreSQL
SELECT id, customer_id, order_date, amount
FROM orders
WHERE order_date < '2026-06-01 12:00:00'
   OR (order_date = '2026-06-01 12:00:00' AND id < 1000)
ORDER BY order_date DESC, id DESC
LIMIT 20;

它的運作方式

The WHERE clause expresses 'strictly after the last row I saw' using the same composite key the ORDER BY sorts by. The engine seeks straight into the index on (order_date DESC, id DESC) instead of counting out skipped rows. The client passes the last row's order_date and id as the cursor; the tie on order_date is broken by id so no row is skipped or repeated.

Variations

Row-value comparison (PostgreSQL, MySQL, SQLite)

PostgreSQL MySQL SQLite
SELECT id, customer_id, order_date, amount
FROM orders
WHERE (order_date, id) < ('2026-06-01 12:00:00', 1000)
ORDER BY order_date DESC, id DESC
LIMIT 20;

SQL Server: OFFSET 0 ROWS FETCH NEXT

SQL Server
SELECT id, customer_id, order_date, amount
FROM orders
WHERE order_date < '2026-06-01 12:00:00'
   OR (order_date = '2026-06-01 12:00:00' AND id < 1000)
ORDER BY order_date DESC, id DESC
OFFSET 0 ROWS FETCH NEXT 20 ROWS ONLY;

Oracle: TIMESTAMP literal and FETCH FIRST

Oracle
SELECT id, customer_id, order_date, amount
FROM orders
WHERE order_date < TIMESTAMP '2026-06-01 12:00:00'
   OR (order_date = TIMESTAMP '2026-06-01 12:00:00' AND id < 1000)
ORDER BY order_date DESC, id DESC
FETCH FIRST 20 ROWS ONLY;

Questions that come up

What does the cursor need to contain?

The values of the last row for every column in the ORDER BY, in order. That is why a unique tiebreaker column belongs in the sort: without it two rows can tie and the cursor cannot say which one came last.

Can users jump to page 37?

Not directly, which is the trade-off. Keyset pagination gives you next/previous; a numbered page index needs OFFSET or a precomputed page table. Most APIs are fine with next/previous.

Keep reading

// snippets are better with a schema brain

Run these with autocomplete that knows your tables

SQLly is a native SQL workbench for macOS, Windows and Linux. Paste a snippet into a live connection and you get schema-aware IntelliSense, a plan viewer and guards against unsafe edits.