Implement keyset pagination: query after the last sort key
Keyset pagination fetches the next page using rows after the previous page's final sort key instead of skipping preceding rows. This avoids repeatedly calculating a large offset when moving forward sequentially. It requires a unique, consistent ordering and is not suited to arbitrary jumps to a numbered page.
Keyset pagination fetches the next page using rows after the previous page's final sort key instead of skipping preceding rows. This avoids repeatedly calculating a large offset when moving forward sequentially. It requires a unique, consistent ordering and is not suited to arbitrary jumps to a numbered page.
Use the last row's key as the boundary
Suppose PostgreSQL 17 sorts by created_at and unique id in ascending order. If the last row on the first page has keys ('2026-04-10 09:30:00+00', 42), the next query can start with tuples greater than that pair:
SELECT id, created_at, total
FROM orders
WHERE (created_at, id) > (:last_created_at, :last_id)
ORDER BY created_at ASC, id ASC
LIMIT 20;PostgreSQL row comparisons compare fields from left to right; the first unequal pair determines the result. If created_at ties, id breaks the tie, so the same (created_at, id) is not returned again. Pass every sort key from the final row to the next request for this reason. This is an explanatory example, not an executed query.
Design the sort and predicate together
The WHERE comparison must match ORDER BY: for ascending order, continue with values greater than the last key (>); for descending order, continue with smaller values (<). Keep filters, sort order, and tie-breaker keys consistent between pages.
With mixed sort directions, a simple tuple comparison may not express the intended order. For created_at DESC, id ASC, the predicate can be expanded as follows:
WHERE created_at < :last_created_at
OR (created_at = :last_created_at AND id > :last_id)
ORDER BY created_at DESC, id ASC
LIMIT 20;This PostgreSQL 17 example is illustrative and assumes the columns are non-null. For nullable sort keys, expression-based ordering, or another database's tuple semantics, make sure the predicate matches the ordering and NULL placement explicitly. PostgreSQL documents that a decisive NULL pair in a row comparison can make the comparison unknown rather than true or false.
When an index can help
The query bounds the next page and seeks after the previous sort key. An index matching the filters and order may allow the storage engine to read rows in order. PostgreSQL B-tree indexes can provide sorted output, and a matching index may help retrieve the needed leading rows for ORDER BY with LIMIT. The planner's actual choice depends on selectivity, data size, and the query, so inspect the execution plan. Indexes also add storage and write-maintenance costs.
For a tenant filter followed by (created_at, id) traversal, a composite index may be a candidate, but useful column order and direction depend on the real predicates and data. Do not assume an index made the query faster; compare EXPLAIN plans and latency on representative data.
Use cases and limits
Keyset pagination can suit sequential traversal of an ordered list, such as next/previous navigation, especially when continuing deep into a large result. Offset is more direct when users must jump to an arbitrary page, such as page 37. With keyset pagination, locating a numbered page may require saved positions or extra queries.
Keyset conditions reduce the positional shift caused by inserts before an offset boundary, but do not freeze results at one point in time. A changed sort key or new row after the current cursor can affect later pages; deleted rows will no longer appear. If an exact whole result from one moment is required, check for a separate snapshot or export boundary supported by the API or storage system.
The keyset algorithm and a cursor token are related but distinct. A server can expose the last sort keys directly or conceal them, possibly with snapshot state, inside an opaque cursor token. The API defines the token contract; keyset describes the predicate used to find the next slice of data.
Implementation checklist
Choose a key combination that makes the result order unique and retain every sort key from the final row.
Match the `>` or `<` predicate to the sort direction; write explicit logic for mixed directions.
Review NULLs, filter changes, concurrent inserts/deletes, and sort-key updates.
Inspect query plans and latency with representative data; weigh index read benefits against write cost.
Decide whether the product needs arbitrary page jumps or sequential traversal; verify separate snapshot/export support for point-in-time consistency.
Sources
[PostgreSQL 17: Row and Array Comparisons](https://www.postgresql.org/docs/17/functions-comparisons.html)
[PostgreSQL 17: Indexes and ORDER BY](https://www.postgresql.org/docs/17/indexes-ordering.html)
[Microsoft EF Core: Efficient Querying](https://learn.microsoft.com/en-us/ef/core/performance/efficient-querying)
[Elasticsearch: Paginate search results](https://www.elastic.co/docs/reference/elasticsearch/rest-apis/paginate-search-results)