← Back to SQL, page 13

sql-0247 · Medium mid

What problems does LIMIT ... OFFSET pagination have on large or changing tables?

The engine still reads and discards every skipped row, so page 10,000 costs as much as reading 10,000 pages. And if rows are inserted or deleted between page requests, items shift: a reader can see the same row twice or miss one. Keyset pagination, which continues after the last row seen, avoids both problems.

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 2 with three posts per page, newest first:

sql
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 3;
idcreatedtitle
52026-03-04e
42026-03-03d
32026-03-02c

A new post arrives before the reader asks for page 3:

sql
INSERT INTO posts VALUES (9, '2026-03-07', 'i');
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 6;
idcreatedtitle
32026-03-02c
22026-03-02b
12026-03-01a

Post 3 ('c') was the last row of page 2 and now appears again at the top of page 3, because every row shifted down by one. Deleting a row would cause the opposite problem, a skipped post.

The cost side: OFFSET 100000 makes the engine walk 100,000 index entries or rows before returning anything. That is fine for small admin tables and a known problem for infinite feeds and API exports.

OFFSET remains reasonable when users jump to arbitrary page numbers on modest data, because keyset pagination cannot jump directly to page 37.

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 OFFSET 3;

INSERT INTO posts VALUES (9, '2026-03-07', 'i');
SELECT id, created, title FROM posts ORDER BY created DESC, id DESC LIMIT 3 OFFSET 6;

Checked on SQLite 3.46.1, run twice with identical output.

Key points

  • OFFSET reads and discards the skipped rows
  • Deep pages get slower
  • Inserts and deletes shift rows between pages
  • Keyset pagination fixes both, but cannot jump to page N

Common mistakes

  • Using OFFSET for infinite scroll on large tables
  • Paginating without a deterministic ORDER BY

Follow-ups

  • How does keyset pagination work?
  • How would you show total pages cheaply?

Tips

  • Demonstrate the duplicate row after an insert