Full answer
sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);Page 1:
sql
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3;| id | created | title |
|---|---|---|
| 8 | 2026-03-06 | h |
| 7 | 2026-03-05 | g |
| 6 | 2026-03-05 | f |
The last row shown is (2026-03-05, 6). The next page continues from there:
sql
SELECT id, created, title FROM posts
WHERE (created, id) < ('2026-03-05', 6)
ORDER BY created DESC, id DESC LIMIT 3;| id | created | title |
|---|---|---|
| 5 | 2026-03-04 | e |
| 4 | 2026-03-03 | d |
| 3 | 2026-03-02 | c |
The row-value comparison (created, id) < ('2026-03-05', 6) means "earlier date, or the same date with a smaller id". Without the id, post 7 or 6 could be skipped or repeated, because two posts share 5 March. SQLite 3.15+ and PostgreSQL support row values; elsewhere, write the expanded form created < ? OR (created = ? AND id < ?).
The plan seeks into the index instead of skipping rows:
sql
EXPLAIN QUERY PLAN SELECT id FROM posts WHERE (created, id) < ('2026-03-05', 6) ORDER BY created DESC, id DESC LIMIT 3;text
QUERY PLAN
SEARCH posts USING COVERING INDEX posts_created_id (created<?)sql
CREATE TABLE posts (id INTEGER PRIMARY KEY, created TEXT NOT NULL, title TEXT);
INSERT INTO posts VALUES
(1,'2026-03-01','a'),(2,'2026-03-02','b'),(3,'2026-03-02','c'),(4,'2026-03-03','d'),
(5,'2026-03-04','e'),(6,'2026-03-05','f'),(7,'2026-03-05','g'),(8,'2026-03-06','h');
CREATE INDEX posts_created_id ON posts(created, id);
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3;
SELECT id, created, title FROM posts
WHERE (created, id) < ('2026-03-05', 6)
ORDER BY created DESC, id DESC LIMIT 3;
EXPLAIN QUERY PLAN SELECT id FROM posts WHERE (created, id) < ('2026-03-05', 6) ORDER BY created DESC, id DESC LIMIT 3;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Continue after the last row's sort key
- Include a unique column to break ties
- Row values express the tie-break compactly
- An index on the sort columns makes each page a seek
Common mistakes
- Paging on a non-unique column alone
- Passing page numbers instead of the last key
Follow-ups
- How would you page backwards?
- How would you encode the cursor in an API?
Tips
- Explain the tie-breaker with the shared date