Data pagination
LIMIT, OFFSET, keysets, and cursors: selecting ordered ranges, handling changing snapshots, and loading relationships.
· Last updated: 2026-11-07 · 8 min read
Overview
Data pagination cuts a query result into ordered slices and fixes where the next call picks up. If a search endpoint returns twenty-five items at a time, the server has to settle three things together: slice size, a tie-breaking sort order, and the boundary for the next request.
Why does sort order matter so much? Because slicing rows means choosing both how many to fetch and where to resume, and resuming falls apart without a deterministic order; slap a row limit onto an unordered query and repeated calls can return scrambling, overlapping subsets.
Screen layout and storage work do not automatically match. A browser might render only 25 cards while a naive backend still scans the entire table and trims the array in memory, so the API contract, the SQL query, and the UI all need compatible definitions of what a single page actually is.
Three questions separate the main approaches: how position is represented, what locks down the sort order, and what happens when writes land between requests. OFFSET and keyset pagination answer all three differently.
For page numbers and previous/next links on screen, see UI pagination; one navigation bar can sit in front of very different backend queries.
Chronology
June 9, 1999: PostgreSQL 6.5 added LIMIT/OFFSET. Its contemporary SELECT documentation describes limiting the returned rows and selecting their range.1
December 5, 2006: PostgreSQL 8.2 was released. Its row comparisons using
<,<=,>,>=were changed to follow SQL-standard left-to-right semantics, and could be used as index constraints for multicolumn indexes matching the row value.2September 2007: Mark Nottingham’s RFC 5005, “Feed Paging and Archiving,” distinguished complete, paged, and archived web feeds.3
2008: According to the contemporary PostgreSQL 8.4 manual, SQL:2008 introduced
OFFSET … FETCHsyntax alongside existingLIMITclauses.4October 14, 2016: SQLite 3.15.0 introduced row-value comparisons for multi-column keyset predicates.5
OFFSET and row positions
OFFSET simply skips a fixed count of rows at the front of an ordered result before returning the next slice. Page math is trivial. Page three at twenty rows per page means “skip forty, read twenty.”
Yet the server still has to walk past the discarded rows. As the current PostgreSQL manual notes, ordering must uniquely fix every row's position if slices are to stay consistent, and deeper offsets steadily pile on scan work.6
Keysets and row comparisons
Keyset pagination drops row counts altogether and anchors the next query to the last key seen. SQLite’s scrolling-window documentation uses a row-value comparison to jump straight past the previous boundary rather than burning work on a large OFFSET.5
Timestamps alone rarely suffice. When several posts share the same second, pairing the timestamp with a unique ID produces a compound boundary, (created_at, id), where descending order on both columns means the next slice simply asks for tuples smaller than the last one seen, and PostgreSQL's left-to-right row comparison over non-null timestamps and unique IDs fixes an exact sequence even inside identical timestamps.7
SQL positions and API cursors
At the API boundary, the current GraphQL Cursor Connections specification defines edges, pageInfo, first, and after, requiring clients to pass cursors back as opaque tokens without parsing their internals.8
That token stayed opaque for a reason. Inside a base64 cursor might sit an encoded (created_at, id) pair or a server-side session key, so the string format alone never tells you whether the database is running a keyset seek.
Keeping the contract opaque decouples UI controls from query plans. A “load more” button or an infinite scroller just hands back the cursor it received, while the server translates that token into whatever storage lookup fits best.
Pages for navigation and archives for preservation
In RFC 5005, Mark Nottingham cites bandwidth savings and sliding-window access as reasons to split web feeds, drawing a sharp line between a paged feed of volatile slices and an archived feed whose permanent documents let a reader reconstruct the entire history.3
Stepping to the next batch is not the same job as archiving a complete record. Most modern API cursors are built for live browsing rather than RFC 5005 archiving, yet that split between browsing a moving stream and capturing a fixed set still shapes pagination design today.
Changing lists and fixed results
New writes expose the difference immediately. Insert a row at the top of a list and every subsequent OFFSET shifts by one, duplicating an item on the next page, whereas keyset pagination dodges that row-count shift while still reflecting updates to sort keys or filter matches.
If each HTTP call grabs a fresh snapshot, the user is walking across a moving floor. Under PostgreSQL Read Committed, even separate statements inside the same transaction can see brand-new snapshots.9
Jobs that must export every record once and only once therefore need a pinned snapshot or a materialized result ID, bringing RFC 5005's old split between live pages and preserved archives right back as a database snapshot boundary.
Relationship loading and N+1
Slicing parent rows also collides with relationship loading. In the classic N+1 pattern, one query fetches twenty parent rows and twenty follow-up queries fetch their children one by one, proving that bounding the parent slice does not bound total query count.
SQLAlchemy's relationship-loading guide traces how lazy loading triggers those extra round-trips and how batch strategies such as select-IN collapse them.10
Never slap a raw LIMIT onto a one-to-many join! If you do, the database counts multiplied child rows instead of parents, so slice the parent IDs first and load their relationships second, settling the counted unit, the sort key, and the snapshot boundary together.
Finding the next range with a compound key
In the PostgreSQL example below, posts A and B share a timestamp, so a unique ID breaks the tie and the first page's final tuple (100, 1) becomes the cutoff for page two.
CREATE TEMP TABLE posts (
id integer PRIMARY KEY,
created_at integer NOT NULL,
title text NOT NULL
);
INSERT INTO posts VALUES
(1, 100, 'A'), (2, 100, 'B'),
(3, 90, 'C'), (4, 80, 'D');
SELECT id, title FROM posts
ORDER BY created_at DESC, id DESC
LIMIT 2;
SELECT id, title FROM posts
WHERE (created_at, id) < (100, 1)
ORDER BY created_at DESC, id DESC
LIMIT 2;
Page one returns B and A; page two picks up strictly below (100, 1) to return C and D. Matching the descending sort (DESC, DESC) with < keeps the boundary tight.
See also
Footnotes
- PostgreSQL 6.5, SELECT syntax and release notes, New SQL features, June 9, 1999. Contemporary SELECT documentation, release notes, release history. ↩
- PostgreSQL 8.2 Release Notes, “Migration to Version 8.2” and “Query Changes.” Released December 5, 2006. Official documentation. ↩
- Mark Nottingham, RFC 5005, “Feed Paging and Archiving,” September 2007, §§1–4. Distinguishes temporary pages from permanent archive documents. RFC. ↩
- PostgreSQL 8.4, “SELECT,” LIMIT/OFFSET and Compatibility. A contemporary implementation manual describing SQL:2008's OFFSET … FETCH syntax. Official manual. ↩
- SQLite, “Row Values,” §3.1 and §4. Official documentation. ↩
- PostgreSQL 18, §7.6 “LIMIT and OFFSET.” Official documentation. ↩
- PostgreSQL 18, §9.25.5 “Row Constructor Comparison.” Official documentation. ↩
- Relay, “GraphQL Cursor Connections Specification,” §§2–5. Specification. ↩
- PostgreSQL 18, §13.2 “Transaction Isolation.” Official documentation. ↩
- SQLAlchemy 2.0, “Relationship Loading Techniques.” Official documentation. ↩