Full answer
CREATE TABLE feed (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT);
INSERT INTO feed VALUES (1,'2026-03-01','a'),(2,'2026-03-01','b'),(3,'2026-03-01','c'),(4,'2026-03-01','d'),(5,'2026-03-02','e'),(6,'2026-03-02','f');The query as written:
SELECT id, created_at FROM feed ORDER BY created_at LIMIT 3 OFFSET 0;| id | created_at |
|---|---|
| 1 | 2026-03-01 |
| 2 | 2026-03-01 |
| 3 | 2026-03-01 |
Four rows share 1 March, so the first page of three could contain any three of them. The database is free to return a different three for the next page, and nothing in the query makes the order repeatable; this run happens to show insertion order, which is an accident of the current plan, not a guarantee.
A corrected version:
SELECT id, created_at FROM feed WHERE (created_at, id) > ('2026-03-01', 3) ORDER BY created_at, id LIMIT 3;| id | created_at |
|---|---|
| 4 | 2026-03-01 |
| 5 | 2026-03-02 |
| 6 | 2026-03-02 |
With ORDER BY created_at, id every row has one fixed position, so page boundaries are stable. The corrected query uses keyset pagination: it asks for the rows after the last seen pair (1 March, id 3), returning row 4 and then the two 2 March rows, with no OFFSET and no overlap. Row-value comparison works in SQLite 3.15+ and in PostgreSQL, and an index on (created_at, id) makes each page cheap.
CREATE TABLE feed (id INTEGER PRIMARY KEY, created_at TEXT, title TEXT);
INSERT INTO feed VALUES (1,'2026-03-01','a'),(2,'2026-03-01','b'),(3,'2026-03-01','c'),(4,'2026-03-01','d'),(5,'2026-03-02','e'),(6,'2026-03-02','f');
SELECT id, created_at FROM feed ORDER BY created_at LIMIT 3 OFFSET 0;
SELECT id, created_at FROM feed WHERE (created_at, id) > ('2026-03-01', 3) ORDER BY created_at, id LIMIT 3;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Ties have no defined order
- Add a unique tie-breaker to ORDER BY
- Keyset pagination avoids OFFSET
- Row-value comparison handles two sort keys
- Index the sort columns together
Common mistakes
- Paginating on a non-unique column alone
- Assuming the insertion order will be repeated
Follow-ups
- How would you paginate backwards?
- How would an API hand the next-page position to the client?
Tips
- Name the tie-breaker