Keyset pagination

Also known as: seek method · cursor-based pagination

On this page 7

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:

  1. The client sends the sort values of the last row on the previous page, often encoded as an opaque cursor token.
  2. The query applies a row value comparison such as (created_at, id) < (:last_ts, :last_id).
  3. The optimizer chooses an index seek on the composite index (created_at, id) and stops after LIMIT rows.
  4. 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 depthOFFSET paginationKeyset pagination
First pageFast, reads about LIMIT rowsFast, reads about LIMIT rows
Page 100Reads and discards thousands of rowsIndex seek plus LIMIT rows
Page 10,000Reads and discards hundreds of thousands of rowsIndex seek plus LIMIT rows
Last pageClose to a full ordered scanIndex seek plus LIMIT rows
Cost of fetching a page by method and depth

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.

RequirementWhy it mattersSymptom when missing
Unique sort keyDefines one exact boundaryMissing or repeated rows between pages
Matching composite indexEnables a seek instead of a sortSlow pages and a sort node in the plan
Consistent sort directionLets one index serve the queryMixed ASC and DESC force extra sorting
Non-null sort columnsKeeps comparisons well definedRows with NULL values never appear
Stable sort valuesPrevents rows from moving between pagesUpdated rows jump ahead or behind
Keyset requirements and failure modes

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.

MethodStrengthsWeaknessesBest fit
LIMIT and OFFSETSimple, supports jumping to page NLinear cost, unstable under writesSmall admin lists
Keyset paginationConstant cost, stable under insertsNo direct jump to page NFeeds, APIs, exports
Server-side cursorExact snapshot of one queryHolds a connection and memoryBatch jobs in one session
Precomputed page tableFast random accessMust be rebuilt as data changesRarely changing catalogs
Comparison of common paging methods

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.

SituationRecommended approachReason
Infinite scroll feedKeyset with opaque cursorConstant latency and no duplicates
Full table exportKeyset on primary keyResumable after failure
Search results with page numbersOFFSET with a capped depthUsers rarely go past a few pages
Total count requiredSeparate estimated countExact counts are expensive
Sorting by user-chosen columnKeyset with column plus primary keyTiebreaker keeps order total
Choosing a paging strategy

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 COALESCE or 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.