SteelReed

Search

Search posts, questions…

SQL & Query TuningQuestion 31 / 37

Middle

What are LIMIT and OFFSET for? Why is a large OFFSET slow, and what do you use instead?

Short answer

LIMIT 20 OFFSET 100000 forces the database to read and throw away 100,000 rows before returning 20, so deeper pages get slower. Keyset pagination remembers the sort values of the previous page's last row and filters WHERE (created_at, id) < (?, ?): each page is one index seek.

OFFSET 100000LIMIT 20Reads 100,020 rowsdiscards 100,000Keyset: filter afterlast row, LIMIT 20One index seekreads 20 rows

3 points to say:

  1. OFFSET n reads and discards n rows: deeper pages get slower, linearly.
  2. Keyset filters on the previous page's last row, one index seek per page; always add id as a tiebreaker.
  3. Need page numbers: cap the depth or use a deferred join.

Keep reading the deep dive

Create a free account to read the full explanation and follow-up questions, mark questions as studied and review them on a schedule.