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.

SqlData Fetching

Code

sqlsnippet
9 lines
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

FAQ

Which relations are involved here?
`articles` — referenced directly, no join needed.