Deep-page pagination → closed keyset window
OFFSET 100000 reads and discards 100,000 rows. In KDBS, keyset pagination bounded at only one end also walks down from the start and reads the same amount. Only a tuple key window closed at both ends reads just one page.
SQL
Situation
The order list screen shows 20 orders per page, newest first. Opening page 5,001 makes the response slow.
Tables
| Table | Column | Type | Description |
|---|---|---|---|
orders | ord_id | int64 | Tuple key. The table is stored in this order |
Page 5,001
BEFORE · OFFSET
SELECT *
FROM orders
ORDER BY ord_id DESC
LIMIT 20 OFFSET 100000
Run it and look at the A-Rows and Buffers of the Scan step.
Approach
1. See what OFFSET reads
OFFSET must also read the rows it skips. There is no way to go directly to the start position.
2. Continue from the last key seen (keyset)
Keep the last ord_id of the previous page and continue reading with WHERE ord_id < :last.
3. In KDBS, close both ends of the window
A KDBS tuple key range search goes directly to the low end only when the window is closed at both ends. A window bounded at only one end walks down from the start and filters. ord_id has no gaps, so the window for one page is (:last - 20, :last).
Explanation
OFFSET → keyset (one end)
AFTER · Keyset (one end)
SELECT *
FROM orders
WHERE ord_id < 1900001
ORDER BY ord_id DESC
LIMIT 20
- The result is the same as Before (20 rows from 1,900,000). But Buffers is also the same as Before, 1,206.
Scan … order=tuple_key_descwalks down from the end of the table and filters 100,000 rows until it meetsord_id < 1900001. In another DB, the tuning would have ended here.
Keyset (closed window)
AFTER · Keyset (closed window)
SELECT *
FROM orders
WHERE ord_id <= 1900000
AND ord_id > 1899980
ORDER BY ord_id DESC
LIMIT 20
Why it got faster
Range orders range=[1899981, 1900000]: it descends the B+ tree once to the low end, reads 20 rows, and stops. Buffers 1.- Before and the one-end keyset took 1,206 pages (100,000 rows). The deeper the page, the larger the gap.
If the key has gaps
When contiguity is not guaranteed as with ord_id, one window may not hold 20 rows. In that case, take a generous window (ord_id > :last - 1000) and cut with LIMIT 20. Only rows inside the window are read, so the cost is proportional to the window size. Paginating by a column that is not the tuple key (e.g. ord_dt) needs an index starting with that column, and here too it must be a closed BETWEEN to be read as a range.
Key points
OFFSET nreads and discards n rows (common to all DBs).- A KDBS tuple key range goes directly to the start position only when both ends are closed. Check in
ANALYZEwhether it isRange … range=[a, b]orScan. - When paginating a join result, use
ORDER BYand paginate by a key unique in the result. Without it, the order can differ from page to page depending on the join order the engine chose.