Deep page pagination → keyset pagination

Replaces OFFSET pagination, which slows down on later pages, with reading from the last key of the previous page.

SQL

Situation

A screen shows paid orders in pages of 20. The first page is fast, but it gets slower as the user moves to later pages. Opening page 5,001 (rows 100,001 to 100,020) takes hundreds of milliseconds.

Tables

TableColumnTypeDescription
ordersstatusvarchar(10)PAID is about 140,000 rows
ordersord_dt, ord_idSort key (newest first; ID descending for the same time)
IndexColumns
orders_pk (clustered)ord_id
orders_x2status, ord_dt, ord_id

Page 5,001

BEFORE · OFFSET pagination

-- Rows 100,001 to 100,020 (page 5,001 at 20 rows per page)
SELECT *
FROM orders
WHERE status = 'PAID'
ORDER BY ord_dt DESC, ord_id DESC
OFFSET 100000 ROWS FETCH NEXT 20 ROWS ONLY

Run it and check how many rows the sort operator handled.

Approach

1. Count the discarded rows

OFFSET 100000 means skip the first 100,000 rows, not avoid reading them. To show 20 rows it produces 100,020 rows and discards 100,000.

2. Check whether "which position" can become "starting where"

If the last row of the previous page (ord_dt, ord_id) is known, reading just 20 rows right after that row is enough. If the index is sorted in the same order, that position can be reached directly.

Explanation

OFFSET → keyset pagination

AFTER · Keyset pagination

SELECT TOP (20) *
FROM orders
WHERE status = 'PAID'
  AND ord_dt <= :last_dt
  AND (ord_dt < :last_dt OR ord_id < :last_id)
ORDER BY ord_dt DESC, ord_id DESC

:last_dt and :last_id are the values of the last row on the previous page (the sandbox passes them as the @last_dt and @last_id parameters).

Why it got faster

  • Before reads 139,682 paid orders with a Clustered Index Scan (Buffers about 13,200), sorts up to 100,020 rows with Sort (TopN Sort), and discards the first 100,000.
  • After reads 20 rows of orders_x2 with a backward Index Seek from the (PAID, last_dt, last_id) position and finishes with 20 Key Lookups. Buffers about 47. The cost is the same for any page.

Why this is optimal

  • It reads only the 20 rows shown on screen and their Key Lookups.
  • Including ord_id in the sort key gives rows with the same time a single order. This keeps rows from being dropped or duplicated at page boundaries.

Key points

  • OFFSET n reads n rows and discards them. The deeper the page, the slower it gets.
  • Keyset pagination is "N rows after the previous last key", so it is constant regardless of page depth. In exchange, "jump straight to page 37" is hard.
  • The sort key must match the index order and be unique (ord_dt, ord_id).
  • DB differences: the same problem occurs with Oracle's triple-nested ROWNUM inline view or OFFSET … FETCH, and PostgreSQL's OFFSET … LIMIT. The keyset method is the same in every DB.