← Back to SQL, page 25

sql-0497 · Medium mid

Pagination with ORDER BY created_at LIMIT 3 OFFSET n shows the same order on two pages and skips another. Why, and how is it fixed?

When several rows share the same sort value, their relative order is not defined, so each page query may order the ties differently and rows can repeat or vanish between pages. Add a unique tie-breaker such as the id to ORDER BY, so every page sees one total order. For deep pages, keyset pagination avoids OFFSET entirely.

Full answer
sql
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:

sql
SELECT id, created_at FROM feed ORDER BY created_at LIMIT 3 OFFSET 0;
idcreated_at
12026-03-01
22026-03-01
32026-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:

sql
SELECT id, created_at FROM feed WHERE (created_at, id) > ('2026-03-01', 3) ORDER BY created_at, id LIMIT 3;
idcreated_at
42026-03-01
52026-03-02
62026-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.

sql
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