Medium java backend

Keyset pagination instead of OFFSET

The 30 second answer

OFFSET pagination makes the database read and throw away every skipped row, so deep pages get slower and slower. Keyset pagination remembers the last sort key from the previous page and asks for rows after it, using an index. Each page then costs about the same. The trade-off is that users cannot jump to an arbitrary page number, only next and previous.

With OFFSET the database still produces and throws away all skipped rows, so deep pages get slower. Keyset (or "seek") pagination remembers the last row's key and continues from there using an index.

SELECT id, title FROM posts WHERE (created_at, id) < (?, ?) ORDER BY created_at DESC, id DESC LIMIT 20;
Sources (2)
  1. PostgreSQL 17: LIMIT and OFFSET
  2. Use The Index, Luke: Paging Through Results