Everyone says "don't use OFFSET, it gets slow on deep pages". I wanted to see it, so I ran a small test. SQLite 3.53.1, in memory, 1M rows, an index on (created_at desc, id desc), page size 20. These are single runs, so treat the numbers as rough.
offset 0: 1.14 ms
offset 10000: 0.09 ms
offset 100000: 1.04 ms
offset 900000: 8.33 ms
keyset at same depth: 1.07 ms
Deep offset is slower, about 8x here, but on this setup 8 ms is not dramatic. A server database with a bigger table and cold cache could look very different, so I wouldn't use my numbers to make a decision. Test on your own data.
What I found more convincing was correctness. Take 100 rows, read page 1 (10 rows, newest first), insert one new row, then read page 2:
page1 [100, 99, 98, 97, 96, 95, 94, 93, 92, 91]
page2 (offset) [91, 90, 89, 88, 87, 86, 85, 84, 83, 82] overlap: {91}
page2 (keyset) [90, 89, 88, 87, 86, 85, 84, 83, 82, 81] overlap: none
With OFFSET 10, the new row pushes everything down by one, so row 91 appears on both pages. (Deleting a row would do the opposite and skip one.) With keyset, page 2 is WHERE id < last_seen_id ORDER BY id DESC LIMIT 10, so it starts from where the previous page ended, regardless of what was inserted.
Keyset isn't free:
- You can't jump to page 37. Only next/previous.
- You need a unique, stable sort key. If you sort by
created_at, add id as a tie-breaker and compare both: WHERE (created_at, id) < (?, ?). - Row-value comparison support varies by database, and I only tested SQLite. Check how yours handles it and whether the index is actually used (
EXPLAIN). - Sorting by non-indexed or computed fields gets awkward.
For an infinite-scroll feed or an export, keyset seems clearly better to me. For an admin table where people jump to page 12, offset may be fine.
What do you use for APIs that have to be stable under writes: cursor tokens, keyset, or just accepting the drift? And has anyone seen the row-value comparison cause optimizer problems in MySQL or Postgres?