Keyset pagination is a technique for reading large ordered result sets page by page in which each request filters on the sort key of the last row already returned instead of telling the database how many rows to skip. Also called the seek method or cursor-based pagination, it is one of the most effective query patterns for performance in databases, because the cost of fetching page 1,000 is roughly the same as the cost of fetching page 1.
The approach replaces the familiar LIMIT ... OFFSET ... pattern with a range predicate on an indexed, unique ordering, such as WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 50. The client keeps the values of the last row it received and sends them back as the starting point for the next page.
How keyset pagination seeks into an index
Keyset pagination works by turning every page request into an index range scan that starts at a known position. When a B-tree index matches the ORDER BY clause, the engine descends the tree directly to the last seen key, which costs a logarithmic number of page reads, and then reads forward only as many entries as the LIMIT requests.
OFFSET pagination behaves very differently. To return rows 100,001 to 100,050, the engine must still produce and discard the first 100,000 rows, because OFFSET is applied after ordering. Work grows linearly with page depth, so deep pages consume CPU, buffer pool space and I/O for rows that nobody sees.
The sequence of a keyset request follows a fixed pattern that the execution plan makes visible:
- The client sends the sort values of the last row on the previous page, often encoded as an opaque cursor token.
- The query applies a row value comparison such as
(created_at, id) < (:last_ts, :last_id). - The optimizer chooses an index seek on the composite index
(created_at, id)and stops after LIMIT rows. - The server returns the rows plus a new cursor built from the final row of the page.
The following table contrasts the cost profile of both approaches for a table with tens of millions of rows.
| Page depth | OFFSET pagination | Keyset pagination |
|---|---|---|
| First page | Fast, reads about LIMIT rows | Fast, reads about LIMIT rows |
| Page 100 | Reads and discards thousands of rows | Index seek plus LIMIT rows |
| Page 10,000 | Reads and discards hundreds of thousands of rows | Index seek plus LIMIT rows |
| Last page | Close to a full ordered scan | Index seek plus LIMIT rows |
Requirements for a correct keyset
A keyset is correct only when the ordering is total and deterministic, which means that no two rows may share the same complete sort key. Sorting by a timestamp alone breaks this rule as soon as two rows have the same value, and rows at the page boundary can be silently skipped or duplicated.
The standard fix is to append a unique tiebreaker column, usually the primary key, to both the ORDER BY clause and the cursor. The index must then cover the same columns in the same order and direction, or the planner falls back to sorting the filtered set, which removes most of the benefit.
The requirements below summarize what a production keyset needs and what fails when each one is missing.
| Requirement | Why it matters | Symptom when missing |
|---|---|---|
| Unique sort key | Defines one exact boundary | Missing or repeated rows between pages |
| Matching composite index | Enables a seek instead of a sort | Slow pages and a sort node in the plan |
| Consistent sort direction | Lets one index serve the query | Mixed ASC and DESC force extra sorting |
| Non-null sort columns | Keeps comparisons well defined | Rows with NULL values never appear |
| Stable sort values | Prevents rows from moving between pages | Updated rows jump ahead or behind |
Row value comparisons such as (a, b) > (x, y) are defined in the SQL standard and are supported efficiently by PostgreSQL, MySQL 8 and SQLite. Some engines do not use an index for that syntax, so the predicate must be expanded to a > x OR (a = x AND b > y), and the execution plan should be checked to confirm that an index seek still occurs.
Keyset pagination compared with other paging methods
Keyset pagination is the preferred method when users or programs move sequentially through large result sets, while OFFSET remains acceptable for small tables or shallow pages. Server-side cursors are a third option, but they hold resources on the server between requests.
| Method | Strengths | Weaknesses | Best fit |
|---|---|---|---|
| LIMIT and OFFSET | Simple, supports jumping to page N | Linear cost, unstable under writes | Small admin lists |
| Keyset pagination | Constant cost, stable under inserts | No direct jump to page N | Feeds, APIs, exports |
| Server-side cursor | Exact snapshot of one query | Holds a connection and memory | Batch jobs in one session |
| Precomputed page table | Fast random access | Must be rebuilt as data changes | Rarely changing catalogs |
Keyset pagination also behaves better under concurrent writes. With OFFSET, an insert near the top shifts every later row, so the next page repeats a row that the client has already seen. A keyset boundary is anchored to a value rather than a position, so new rows appear only where they belong in the order.
Designing APIs and queries around keysets
In application design, keyset pagination is usually exposed through opaque cursor tokens rather than raw column values. The server serializes the last sort values, often with Base64 encoding and a signature, so clients cannot depend on the internal schema or tamper with the boundary.
Backward navigation uses the reverse comparison and the reverse ORDER BY, then flips the fetched rows in the application before display. Fetching LIMIT plus one row is a cheap way to know whether a next page exists without running a separate COUNT query.
The decision table below shows how common requirements translate into a paging choice.
| Situation | Recommended approach | Reason |
|---|---|---|
| Infinite scroll feed | Keyset with opaque cursor | Constant latency and no duplicates |
| Full table export | Keyset on primary key | Resumable after failure |
| Search results with page numbers | OFFSET with a capped depth | Users rarely go past a few pages |
| Total count required | Separate estimated count | Exact counts are expensive |
| Sorting by user-chosen column | Keyset with column plus primary key | Tiebreaker keeps order total |
Limitations and common mistakes
The main limitation of keyset pagination is that it cannot jump directly to an arbitrary page number, because the boundary of page 500 is unknown until pages 1 to 499 have been read. Interfaces that require numbered pages must either cap the depth, approximate the jump or accept OFFSET for that feature.
- Omitting the tiebreaker creates intermittent gaps that are hard to reproduce in testing.
- Sorting on expressions such as
lower(name)requires an expression index with the same definition. - Filtering on nullable columns needs explicit NULL handling, for example
COALESCEor NULLS LAST in both the index and the query. - Exposing raw keys in URLs leaks schema details and lets clients craft unexpected boundaries.
- Changing the sort order between requests invalidates every outstanding cursor.
Keyset pagination also does not provide a consistent snapshot across pages. Rows updated after the first request can move in the order, so a long export that needs exact consistency should run inside a single repeatable read transaction or use a snapshot.
The short version
Imagine reading a very long list one screen at a time. The slow way is to count from the top every time: to see screen 500, you count past everything on screens 1 to 499 first. That counting gets slower and slower the deeper you go.
Keyset pagination works like a bookmark. You remember the last item you saw and ask for the next items after it. The database jumps straight to the bookmark and reads forward, so every screen loads equally fast, no matter how far into the list you are.
Where it makes a difference
An online marketplace offers sellers an order history API that returns 100 orders per call. The orders table holds about 80 million rows. With OFFSET pagination, large sellers who page back through several years of history see response times climb from 20 milliseconds on the first page to more than 4 seconds on deep pages, and the database spends much of its I/O on rows it immediately discards.
The team adds a composite index on (seller_id, created_at, id) and switches the API to a cursor that encodes the last created_at and id. Each call now performs an index seek followed by a 101-row read. Response times stay near 20 milliseconds on every page, duplicate orders caused by concurrent inserts disappear, and nightly export jobs can resume from the last cursor after a network failure instead of starting over.