Sub topic 13
Keyset Pagination as an Alternative
This chapter assumes you can write SELECT queries with WHERE and ORDER BY. It also assumes you know LIMIT and OFFSET, and that you have seen why a large OFFSET gets slow. Here you will replace OFFSET with a condition on the sort keys. You will also learn what that costs you.
The problem keyset pagination solves
With LIMIT 10 OFFSET 20, the database has to produce the first 30 rows in sort order. It then throws away 20 of them and returns 10. The work grows with the offset. Page 1 is cheap. Page 5,000 reads and discards 49,990 rows before it returns anything.
Offset paging has a second problem. If rows are inserted or deleted between two page requests, every row after the change shifts position. A user can see the same row twice, or miss a row entirely.
Keyset pagination (also called seek pagination) avoids both problems. Instead of saying "skip N rows," the query says "give me rows that come after the last row I already showed." The client remembers the sort key values of the last row on the current page. The next query uses those values in a WHERE condition.
The basic pattern
Suppose the first page is fetched like this:
SELECT order_id, order_date, total
FROM orders
ORDER BY order_date DESC, order_id DESC
LIMIT 10;The last row on that page has order_date = '2024-03-15' and order_id = 1042. To get the next page, ask for rows that sort strictly after that row:
SELECT order_id, order_date, total
FROM orders
WHERE (order_date, order_id) < ('2024-03-15', 1042)
ORDER BY order_date DESC, order_id DESC
LIMIT 10;The expression (order_date, order_id) < ('2024-03-15', 1042) is a row-value comparison. It compares the pairs the way ORDER BY sorts them. The first values are compared first. The second values are compared only when the first values are equal. It is supported in PostgreSQL, MySQL, and SQLite 3.15 and later.
Because the query has no OFFSET, the database does not read the skipped rows. With an index on (order_date, order_id), it can jump straight to the starting position and read 10 entries.
Why the tie-breaker is required
The sort key must be unique. Many orders can share an order_date. If you paged on order_date alone, using WHERE order_date < '2024-03-15', you would skip every other order from that day that was not on the previous page. Adding order_id makes each key unique, so every row has exactly one position in the order.
The same rule applies to plain LIMIT. A non-unique ORDER BY can return tied rows in a different order from one query to the next, which makes pages overlap or leave gaps.
Sort direction must match
The comparison operator must agree with the sort direction.
| Sort order | Next-page condition |
|---|---|
| `ORDER BY a DESC, b DESC` | `(a, b) < (last_a, last_b)` |
| `ORDER BY a ASC, b ASC` | `(a, b) > (last_a, last_b)` |
Row-value comparison applies one operator to all columns. It cannot express mixed directions such as a DESC, b ASC. For that case, or in a database without row-value support, write the condition out by hand:
SELECT order_id, order_date, total
FROM orders
WHERE order_date < '2024-03-15'
OR (order_date = '2024-03-15' AND order_id < 1042)
ORDER BY order_date DESC, order_id DESC
LIMIT 10;This is logically the same as the row-value form. For a mixed ordering such as order_date DESC, order_id ASC, you would change only the last comparison to order_id > 1042.
Supporting the query with an index
Keyset pagination is fast only when an index matches the ORDER BY. For the examples above:
CREATE INDEX idx_orders_date_id
ON orders (order_date DESC, order_id DESC);Without this index, the database must still scan and sort many rows to find the page, and you lose most of the benefit. Some systems can scan a plain ascending index backward, so the DESC in the index definition is not always necessary. Check your database's behavior.
Walking through a pagination loop
The application does the bookkeeping. A typical flow looks like this:
- Run the first-page query with no
WHEREcondition. - Read the last row of the result and save its
order_dateandorder_id. This is the cursor. - Send the cursor to the client, often encoded as an opaque string.
- When the client asks for the next page, run the keyset query with the cursor values.
- If fewer rows come back than the page size, there are no more pages.
A common trick is to request LIMIT 11 for a page size of 10. If 11 rows come back, a next page exists. You return only the first 10 and use the 10th row as the cursor.
SELECT order_id, order_date, total
FROM orders
WHERE (order_date, order_id) < ('2024-03-15', 1042)
ORDER BY order_date DESC, order_id DESC
LIMIT 11;Edge cases and gotchas
NULL in sort columns. A comparison with NULL evaluates to unknown, so rows with a NULL sort key are dropped by the WHERE condition. Keep keyset columns NOT NULL, or handle NULL explicitly. Databases also differ on whether NULL sorts first or last, which changes where those rows land.
Mutable sort keys. If the sort column can change, such as updated_at, a row can move to a different position between page requests. It may be missed or shown twice. Prefer immutable columns like creation time and ID.
Consistency under writes. Keyset paging is far more stable than offset paging when rows are inserted. A new row that sorts before the cursor does not shift later pages. It simply is not in the pages you are walking forward through.
Type handling in cursors. Pass the cursor values back with their original types and precision. A timestamp truncated to seconds will not match a stored timestamp with microseconds, and the comparison can repeat or skip rows.
Untrusted cursors. If the cursor comes from the client, treat it as input. Bind the values as query parameters. Never paste them into the SQL string.
Limits of the approach
Keyset pagination is not a drop-in replacement for offset paging.
| Need | Offset | Keyset |
|---|---|---|
| Jump to page 50 directly | Yes | No, you must have the cursor from page 49 |
| Show "page 3 of 120" | Yes, with a count | Awkward |
| Cost of deep pages | Grows with offset | Roughly constant |
| Stable under inserts | No | Mostly |
| Go backward | Easy | Needs reversed order and condition |
To go backward, flip the comparison and the sort direction, then reverse the fetched rows in the application:
SELECT order_id, order_date, total
FROM orders
WHERE (order_date, order_id) > ('2024-03-10', 1001)
ORDER BY order_date ASC, order_id ASC
LIMIT 10;The 10 rows returned are in ascending order. Reverse them in code to show them newest first.
Use keyset pagination for infinite scroll, feeds, exports, and APIs where users move sequentially through large tables. Keep LIMIT/OFFSET for small tables or interfaces that need numbered pages, where deep offsets are rare.
Exercise
A query pages through events with ORDER BY created_at ASC, event_id ASC LIMIT 25. The last row of the current page has created_at = '2025-01-09 08:00:00' and event_id = 700. Write the query for the next page using keyset pagination. Then explain why WHERE created_at > '2025-01-09 08:00:00' alone would be wrong.
Show answer
SELECT eventid, createdat FROM events WHERE (createdat, eventid) > ('2025-01-09 08:00:00', 700) ORDER BY createdat ASC, eventid ASC LIMIT 25; Filtering on createdat alone would skip every other event that has the same timestamp but a larger eventid and was not shown on the previous page, because createdat is not unique. The eventid tie-breaker gives each row a unique position.
Exercise
Name two situations where offset paging is still a better fit than keyset paging.
Show answer
When the interface needs to jump directly to an arbitrary page number or show "page X of Y", and when the table is small enough that the cost of skipping rows is negligible.