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.
3 points to say:
OFFSET nreads and discards n rows: deeper pages get slower, linearly.- Keyset filters on the previous page's last row, one index seek per page; always add
idas a tiebreaker. - 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.