← Back to SQL, page 13

sql-0248 · Medium mid

Write a keyset (seek) pagination query that returns the next page of posts after the last one shown.

Remember the sort key of the last row shown, then ask for rows that come after it: WHERE (created, id) < (:last_created, :last_id) ORDER BY created DESC, id DESC LIMIT 3. Including the unique id breaks ties when several rows share a timestamp. An index on (created, id) lets the engine seek straight to the starting point.

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;
idcreatedtitle
82026-03-06h
72026-03-05g
62026-03-05f

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;
idcreatedtitle
52026-03-04e
42026-03-03d
32026-03-02c

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