Video in progress
How does pagination with LIMIT and OFFSET work, and why does it get slow when OFFSET is large?
LIMIT 20 OFFSET 40 skips 40 rows of the ordered result and takes the next 20. But the database still has to find and read those 40 skipped rows, so with OFFSET 1,000,000 it reads a million rows for nothing.
📖 Answer
SELECT id, title, created_at
FROM articles
ORDER BY created_at DESC, id DESC
LIMIT 20 OFFSET 40; -- page 3
Don't use LIMIT without ORDER BY: the order isn't guaranteed, so the same row can show up on two pages or get skipped. If the sort column isn't unique, add id at the end.
For deep pages the "keyset" (seek) method is much faster:
SELECT id, title, created_at
FROM articles
WHERE (created_at, id) < (:lastCreatedAt, :lastId) -- last row of the previous page
ORDER BY created_at DESC, id DESC
LIMIT 20;
With an index on (created_at, id), this query is equally fast on page 1 and on page 50,000. The downside is that you can't "jump to page 37", only go next or previous. That's why keyset suits feeds and infinite scroll, while OFFSET is enough for small admin tables.
In Spring Data, Pageable uses OFFSET; for keyset there is the ScrollPosition/Window API in 3.1+.
Sign up to mark studied questions and save your progress.