Keyset vs OFFSET Pagination: Stable SQL Pages with Cursors
Build SQL pagination with a unique sort order, composite cursor and matching index. Includes tested tie, insert, delete and previous-page examples.
Use OFFSET for simple numbered pages when skipping rows is acceptable. Use keyset pagination for sequential traversal: continue after the last returned sort key, include a unique tie-breaker, and keep filters and ordering fixed. A cursor avoids positional shifts but does not create a snapshot or prevent rows moving when their sort keys change.
Choose the navigation contract first
A search screen needs a link to page 20. An activity feed needs the next three older records. A nightly export needs to visit a fixed set exactly once. These are different navigation contracts, even if each query has a LIMIT. Start by deciding whether the reader needs numbered jumps, sequential browsing or a consistent export.
OFFSET expresses a position in the current ordered result: skip this many rows, then take a page. Keyset pagination expresses a boundary: take rows that sort after this previously returned key. A cursor is the application representation of that boundary, not a special SQL keyword and not necessarily a database server cursor.
This guide uses an integer created_seq as a small, readable stand-in for a creation-order field. Both sort fields are non-null, and id is unique. The SQL examples and mutation cases were executed in memory with SQLite 3.53.1. PostgreSQL documentation supports the SQL design discussion; no PostgreSQL execution plan or production speedup is claimed.
| Need | Useful starting point | Trade-off |
|---|---|---|
| Small numbered result pages | LIMIT with OFFSET | Simple jumps, but later pages skip more rows |
| Next/previous feed navigation | Keyset with a composite cursor | Requires a known boundary; no natural arbitrary page jump |
| Consistent full export | Snapshot or materialized export contract | Pagination alone cannot freeze membership |
| Exact total page count | Separate count policy | Counting can add work and may observe a different dataset |
A page boundary needs a unique order
ORDER BY created_seq DESC alone does not decide the order of rows sharing the same value. Adding LIMIT does not fix that ambiguity. Use ORDER BY created_seq DESC, id DESC so every row has one position within a fixed dataset. The unique ID acts as a tie-breaker; it need not be the primary business sort.
Keep the complete sort definition consistent in the first-page query, continuation query and cursor. If an API changes its sort from creation order to relevance score, an old cursor no longer describes the same boundary. Treat sort version, filters and tenant scope as part of the cursor contract.
The following disposable fixture has two ties and a row belonging to another tenant. Run it only in a scratch database. The first page for tenant 1 is IDs 109, 108, 107. Their sequence values are 50, 50, 40. Selecting the last row gives the continuation boundary (40, 107).
CREATE TABLE feed_items (
id INTEGER PRIMARY KEY,
tenant_id INTEGER NOT NULL,
created_seq INTEGER NOT NULL,
title TEXT NOT NULL
);
CREATE INDEX feed_items_seek
ON feed_items (tenant_id, created_seq DESC, id DESC);
INSERT INTO feed_items (id, tenant_id, created_seq, title) VALUES
(109, 1, 50, 'A'), (108, 1, 50, 'B'),
(107, 1, 40, 'C'), (106, 1, 30, 'D'),
(105, 1, 30, 'E'), (104, 1, 20, 'F'),
(103, 1, 10, 'G'), (999, 2, 99, 'Other tenant');
SELECT id, created_seq, title
FROM feed_items
WHERE tenant_id = 1
ORDER BY created_seq DESC, id DESC
LIMIT 3;
-- IDs: 109, 108, 107Source: PostgreSQL: LIMIT and OFFSET ↗
Continue after the entire composite key
For descending order on both fields, later rows have a smaller composite key. The next-page predicate compares created_seq first, then id when the sequence is equal. The tuple comparison below returns 106, 105, 104. The expanded OR form shown afterward expresses the same boundary for this non-null, uniformly descending order.
Using only created_seq < 40 happens to work at this particular boundary. It fails when a page ends inside a tie. With a page size of one, the first row is 109 at sequence 50. Seeking only below 50 would skip row 108. Including id allows the next query to retrieve 108 before moving to lower sequence values.
In application code, bind tenant, cursor fields and a validated page size with the database driver’s parameter API. Literal values here make the example reproducible. Do not concatenate a client cursor into SQL. Placeholder syntax varies by driver; maintain a fixed, reviewed sort expression rather than accepting arbitrary SQL from request parameters.
SELECT id, created_seq, title
FROM feed_items
WHERE tenant_id = 1
AND (created_seq, id) < (40, 107)
ORDER BY created_seq DESC, id DESC
LIMIT 3;
-- IDs: 106, 105, 104
-- Equivalent boundary for these NOT NULL columns:
SELECT id, created_seq, title
FROM feed_items
WHERE tenant_id = 1
AND (created_seq < 40 OR (created_seq = 40 AND id < 107))
ORDER BY created_seq DESC, id DESC
LIMIT 3;What an insert or delete changes
Consider separate requests without a shared snapshot. After reading the first page, insert tenant-1 row 110 with sequence 60. The current order begins 110, 109, 108, 107. OFFSET 3 now returns 107, 106, 105: row 107 appears again because the position shifted. The keyset boundary (40, 107) still returns 106, 105, 104.
Reset the fixture, then delete row 109 after the first page. OFFSET 3 returns 105, 104, 103, skipping row 106 relative to the original traversal. The same keyset predicate returns 106, 105, 104 because it seeks by values rather than the count of preceding rows. These outcomes were checked with committed changes between queries in the local fixture.
This is a continuity advantage, not a snapshot guarantee. A newly inserted row below the boundary can appear on a later page. A row deleted before retrieval disappears. If row 106 changes from sequence 30 to 70 before page two, it moves above the saved boundary and will not be seen in the remaining descending traversal. An already seen row moved below the boundary can appear again.
Use a stable, preferably immutable ordering key when the product permits it. If an export must preserve exact membership and values, choose an explicit snapshot or materialization strategy and evaluate its operational cost. PostgreSQL Read Committed statements can observe different snapshots; using keyset predicates across separate requests does not change that isolation contract.
Detect a next page and reverse direction carefully
To expose hasNextPage for a page size of three, request up to four rows. Return the first three and use the extra row only as evidence that more existed for that query. Build the next cursor from the last returned row, not the extra row; otherwise the extra row gets skipped on the next request.
For a previous-page link in a descending feed, use the first returned row as the boundary, seek greater keys, fetch in ascending order, then reverse the selected rows for display. From page two beginning with (30, 106), the query below returns 107, 108, 109. Reversing gives 109, 108, 107, the original first page in this unchanged fixture.
Use separate before and after semantics or an explicit direction field. Reversing the inequality without reversing the query order finds a different slice. Test first-page and last-page boundaries, empty results and tie groups larger than the page size before adding previous-page navigation.
A lookahead row establishes that another row existed while this query ran, not that the next request must return it. If intervening deletes empty the next page, let the API return an empty result with no continuation token. Do not manufacture a page by loosening the cursor predicate. Similarly, a separately calculated total count should state its freshness rather than implying that every later numbered page preserves that membership.
-- Previous page from page two's FIRST returned key (30, 106):
SELECT id, created_seq, title
FROM feed_items
WHERE tenant_id = 1
AND (created_seq, id) > (30, 106)
ORDER BY created_seq ASC, id ASC
LIMIT 3;
-- SQL IDs: 107, 108, 109
-- Reverse these rows in the application: 109, 108, 107Match the index to filtering and ordering
The fixture’s index places tenant_id first because the query fixes that field by equality, followed by the two ordering keys. This is a useful candidate for the shown access pattern, not a universal index recipe. Additional filters, joins, selected columns, data distribution and database behavior affect the plan.
OFFSET still requires skipped rows to be computed. Keyset can allow an index-backed boundary seek followed by a small range scan, but a matching index and useful plan matter. Avoid promising constant latency or a fixed speedup from changing the query text alone. A selective filter applied after scanning may still require inspecting many candidate rows.
Compare plans and representative deep-page requests on your actual engine. Record rows scanned, sort work, buffer activity and latency under comparable conditions. Our PostgreSQL EXPLAIN ANALYZE guide explains how to read that evidence. The eight-row fixture here proves result semantics; it is too small to establish production performance.
Make the cursor precise and validate its scope
A practical token can carry a format version, sort identifier and the last returned key values. Preserve exact types and precision: rounding a timestamp or converting a large integer through an unsafe JavaScript number can move the boundary. Serialize large IDs as decimal strings when the client cannot represent them exactly.
Bind the token to the query’s filters and scope, either by validated token fields or server-side state. Always reapply authorization from the authenticated request. Possessing a cursor for tenant 1 must not authorize reading tenant 1. If cursor integrity matters, use an authenticated token or server-side lookup; base64 encoding alone prevents neither modification nor disclosure.
Set a maximum page size and reject malformed, unsupported or incompatible cursors with a clear client error. An expired cursor should have a documented restart path. A deleted boundary row need not make traversal impossible when the token stores its key values: the continuation query compares values and does not need to look that row up again.
The fixture deliberately excludes NULL sort values. Row comparisons involving NULL may evaluate to unknown, which a WHERE clause does not keep. Define an explicit null placement and matching boundary predicate, or use non-null sort keys. Mixed ASC/DESC ordering also needs a predicate matching each direction; copying a single tuple < expression is not generally correct for mixed directions.
Test continuity, then choose the simplest adequate method
On a static fixture, traverse every page and compare the concatenated IDs with one fully ordered query. Assert no missing or duplicated IDs, including ties that cross a boundary. Then repeat with insertions, deletions and sort-key updates between requests so the product’s consistency expectations are explicit rather than accidental.
Keep OFFSET when numbered jumps and a small result set make it appropriate. Choose keyset for next/previous traversal where a value boundary fits the interaction. For exact exports, add a separate consistency contract. The useful design is the one whose order, cursor and data-change behavior you can test and explain, with query-plan evidence supporting any performance claim.
Your next steps
- Define a total order with a unique tie-breaker and an explicit NULL policy before designing a cursor.
- Seek after the last returned row, bind cursor values as parameters, and keep filters and authorization consistent.
- Test ties and data changes separately from performance; keyset pagination does not promise a frozen dataset.
Sources & official resources
Linked resources checked on 2026-10-24. Technical behavior and provider guidance can change; check the documentation for the version you use.
About this guide and its recommendations
Published by Prep With Proof with AI-assisted drafting. Study routines and examples are editorial suggestions, not official exam instructions or claims of a learner's personal results. Cited provider facts are linked; ownership of recommended Prep With Proof products is disclosed. No competitor endorsement or guaranteed certification outcome is implied.
Suggest a correction →