Dev Learning Lab

The labs on this site need JavaScript to run. The same content is written out below.

Learn › Database › SQL

Offset and keyset pagination

Why later pages get slower

Why it exists — The OFFSET method, which divides by page number, makes the DB read even the rows it skips, so it gets slower toward the later pages of a list with a lot of data, and on screens where the user keeps scrolling down. Keyset (cursor-based) pagination passes the sort key of the last article received as the condition of the next request instead of a page number, and if the sort key has an index, it reduces the number of rows read to the page size, whichever page it is.

Where it's used today — It is used on screens that load continuously as you scroll down, such as feeds, comments, and notifications, and in batch processing that reads a large table in pieces from start to end. Even if new articles come in between pages, the same article does not appear twice. On screens where you must jump to an arbitrary position, such as a bulletin board where you go directly to a desired page number, the OFFSET method is used.

A list of posts is shown page by page, newest first. The OFFSET method reads and discards all the rows of the earlier pages before it reaches the page you want. The keyset (cursor) method uses the index to go straight to "right after the last post you saw".

Checked against real execution · All 60 combinations run on MySQL 8.4 and compared (rows read are Handler_read counters)

Concepts in this lab

Offset-based pagination and keyset (cursor-based) pagination
Offset-based pagination skips a given number of rows from the start and then fetches rows. It gets slower for later pages because all the skipped rows must still be read. Keyset pagination remembers the key value of the last row of the previous page and queries with the condition "after that value". It uses an index to start reading right at that position, so the speed stays constant even for deep pages.
Index
A data structure that keeps the values of specific columns separately, in sorted form, so that the wanted rows of a table can be found quickly. Without one, the whole table must be read to find the rows that match a condition. Reads get faster, but it must also be updated every time data is inserted, updated, or deleted, so it costs write performance and storage space.
B-tree index
Why it exists — A binary tree on disk has one key per node, so its height grows when there are many rows, and it is slow because every node read is a disk read. A B-tree puts many keys in one disk page, so it finds a value with a few page reads.
Where it's used today — In MySQL InnoDB and PostgreSQL, a B-tree index is created when you do not specify the kind with CREATE INDEX. For lookups that only look for the same value, you can also choose a hash index in PostgreSQL.
The index structure that most relational databases use by default. It is a balanced tree that keeps values sorted, and each node holds many keys, so the height of the tree is low. You can find a value by going down only a few levels from the root. Because the values are sorted, it is used not only for equality lookups but also for range lookups and sorting.

Try these

Running with the default settings

  1. The post table has 1,000,000 posts, and a larger id means a newer post. Page 1,000 is requested with OFFSET 19,980.
  2. The database cannot know in advance where the row after the first 19,980 rows is. It starts from the newest post and counts one by one along the index while it reads. It reads 19,980 rows and throws them away.
  3. Then it reads the next 20 rows and returns them as the result. The ids run from 980,020 down to 980,001.

Result of this run

Code

-- Page 1,000 (id descending = newest first)
SELECT id, title, created_at
  FROM post
 ORDER BY id DESC
 LIMIT 20 OFFSET 19980;

Assumptions of this model

All 60 combinations were run on MySQL 8.4.11 against a post table with 1,000,000 posts (id 1 to 1,000,000, with id as the primary key) and compared with this lab. Rows read is the sum of Handler_read_key and Handler_read_prev shown by SHOW SESSION STATUS after the query runs (the number of times a row was read from the storage engine), and rows discarded is that sum minus the number of rows returned. InnoDB counts the single read that starts at the very end of an index in both Handler_read_last and Handler_read_key, so it was counted once. In EXPLAIN, the OFFSET query showed type index, key PRIMARY, and Backward index scan in Extra, and the keyset query with a condition showed type range and key PRIMARY. In MySQL (InnoDB), the primary key index stores the whole row, so reading along this index is reading the rows. For the case where a new post is added in between, another connection really inserted one post and then the next page was read. With OFFSET, the first line of the next page was the last post of the previous page again, and with keyset it was the post that comes next. If the sort key is not id but a column whose values can repeat, such as the creation time, the keyset condition must also include a column whose values do not repeat, as in (creation time, id).

Previous lab: Window functions · Next lab: Views, stored procedures, and triggers

Concepts in this lab

What this lab shows

Settings

Code


      
    

Diagram

Run comparison

Try these