Keyset Pagination Query
Paginate with a WHERE clause on the last seen key instead of OFFSET, keeping each page fast and stable as new rows arrive.
Code
SELECT id, title, created_at
FROM articles
WHERE (created_at, id) < ($1, $2)
AND published = true
ORDER BY created_at DESC, id DESC
LIMIT $3;
-- The caller passes the previous page's created_at and id as cursor values,
-- plus the page size as the limit, so no OFFSET scan is required.How the snippet works
At its core this is a single SELECT statement against articles.
In terms of clauses, the statements use: a WHERE clause constraining which rows the statement operates on; an ORDER BY that fixes the output order; a row cap (LIMIT) bounding the result size.
Applying it
Point it at the articles table — the LIMIT keeps the probe cheap while you tune the predicates.
Statements that matter
SELECT id, title, created_at
FROM articles
WHERE (created_at, id) < ($1, $2)
AND published = true
ORDER BY created_at DESC, id DESC
LIMIT $3;
Interactive Tools for This Topic
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.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.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.GraphQL Query FormatterPretty-print a GraphQL query by indenting selection sets by brace depth and normalizing punctuation spacing.
FAQ
- Which relations are involved here?
- `articles` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.