Scrivio Interview library
CodingFoundations7 min read · updated 12 November 2026

Rewrite this pagination to keyset pagination and explain why it is faster on page 5,000:

SQL
SELECT *
FROM posts
ORDER BY created_at DESC
LIMIT 20 OFFSET 100000;

With OFFSET 100000 the database must read and discard 100,000 rows before it returns 20, so every page is slower than the one before. Keyset pagination remembers where the last page ended and asks for rows after it: WHERE (created_at, id) < (:lastCreatedAt, :lastId) ORDER BY created_at DESC, id DESC LIMIT 20. With an index on (created_at DESC, id DESC), the query seeks straight to that position and reads 20 entries, whatever the page number. The id tie-breaker makes the order unique, and pages stay stable when new rows are inserted.

Why this question is asked

Pagination looks trivial until a table reaches millions of rows and users, crawlers or integrations start requesting deep pages. Then OFFSET queries become one of the most common reasons for a slow API and a busy database. Interviewers give this exercise to see whether we understand why OFFSET degrades and can write a correct keyset query, including the tie-breaker that many people forget. In this answer, we will see what OFFSET really does, write the keyset version step by step, explain the tie-breaker, add the supporting index, compare how both behave when rows are inserted, and show how the cursor flows through a Spring endpoint.

1What OFFSET Really Does

LIMIT 20 OFFSET 100000 sounds like an instruction to jump to row 100,000, but databases cannot jump to a row number. Row numbers are not stored anywhere; they only exist after the rows have been sorted. So the database must produce the rows in order, count off the first 100,000 and throw them away, and only then return 20.

Java
EXPLAIN ANALYZE
SELECT * FROM posts ORDER BY created_at DESC LIMIT 20 OFFSET 100000;
-- Limit (actual time=410.2..410.3 rows=20 loops=1)
-- -> Index Scan Backward using posts_created_at_idx on posts
-- (actual time=0.03..402.8 rows=100020 loops=1)

Notice actual rows=100020: even with a perfect index the scan reads 100,020 entries and table rows to return 20. Page 1 reads 20, page 50 reads 1,000, and page 5,000 reads 100,020, so the cost grows linearly with the page number. Without a usable index it is worse, because the database sorts the whole table first.

2Writing the Keyset Version

Keyset pagination, also called seek pagination, does not count rows. It remembers the sort key of the last row on the previous page and asks for the rows that come after that key. Because we sort newest first, the next page holds rows older than the last one we showed.

SQL
-- first page: no cursor yet
SELECT * FROM posts ORDER BY created_at DESC, id DESC LIMIT 20;
-- last row returned: created_at = '2026-11-01 09:15:00', id = 88412
-- next page: everything after that row in the same order
SELECT * FROM posts
WHERE (created_at, id) < ('2026-11-01 09:15:00', 88412)
ORDER BY created_at DESC, id DESC
LIMIT 20;

The row value comparison (created_at, id) < (a, b) means: created_at is less than a, or created_at equals a and id is less than b. It is exactly the condition for coming after the last row in descending order of created_at, then id. PostgreSQL supports this syntax and can use it directly as an index range condition. MySQL accepts it too, but its optimizer may not use it as a range on the index, so there we often write the expanded form, created_at < :a OR (created_at = :a AND id < :b), and check the plan; check your version.

3Why the Tie-Breaker Matters

Why not just WHERE created_at < :lastCreatedAt? Because created_at is not unique. Imagine 30 posts imported at exactly 09:15:00 and a page boundary that falls after the 12th of them. With created_at < '09:15:00' the next page skips the other 18 completely. With created_at <= it repeats the 12 we already showed. Neither is correct.

Adding id, which is unique, makes the order total: every row has exactly one position, and the cursor (created_at, id) points between two specific rows. The ORDER BY must use the same columns in the same directions as the WHERE condition, or the cursor no longer matches the order.

Page boundary inside equal timestamps
Condition for the next pageRows at 09:15:00 already shownResult
created_at < '09:15:00'12 of 30the other 18 are skipped
created_at <= '09:15:00'12 of 30the 12 shown are repeated
(created_at, id) < ('09:15:00', 88412)12 of 30continues exactly after id 88412

4The Index That Makes It Fast

The keyset query needs an index whose order matches the sort, so the database can seek to the cursor position and read the next 20 entries.

Java
CREATE INDEX posts_created_id_idx ON posts (created_at DESC, id DESC);
EXPLAIN ANALYZE
SELECT * FROM posts WHERE (created_at, id) < ('2026-11-01 09:15:00', 88412)
ORDER BY created_at DESC, id DESC LIMIT 20;
-- Limit (actual time=0.04..0.09 rows=20 loops=1)
-- -> Index Scan using posts_created_id_idx on posts (actual rows=20 loops=1)
-- Index Cond: (ROW(created_at, id) < ROW('2026-11-01 09:15:00', 88412))

Notice actual rows=20 on page 5,000 just as on page 2: the B-tree descends to the position of the cursor in a few page reads and walks forward 20 entries. In PostgreSQL an index on (created_at, id) in ascending order also works, because a B-tree can be scanned backwards; what matters is that both columns go the same direction as in the ORDER BY.

5Stability When Rows Are Inserted

Keyset pages are also more correct. With OFFSET, if 5 new posts are created while a user reads page 1, every older post shifts 5 positions further down, so page 2 starts with the last 5 posts the user already saw on page 1: duplicates. Deletions shift rows the other way, and some are skipped. A keyset cursor points to a key, not a position, so new posts appear before page 1 and the next page simply continues after the last row shown, with no duplicates and no gaps.

6Passing the Cursor Through the API

In a Spring endpoint, the client gets the cursor of the last row with each page and sends it back for the next one. Encoding it, for example as Base64 of the two values, keeps clients from depending on its contents.

Java
record Cursor(Instant createdAt, long id) {}
record CursorPage<T>(List<T> items, String next) {}
@GetMapping("/posts")
CursorPage<PostDto> posts(@RequestParam(required = false) String after) {
Cursor c = after == null ? null : Cursors.decode(after);
List<Post> rows = (c == null)
? repo.firstPage(21) // fetch 21 to know if there is a next page
: repo.pageAfter(c.createdAt(), c.id(), 21);
boolean more = rows.size() > 20;
List<Post> page = rows.subList(0, Math.min(20, rows.size()));
String next = more ? Cursors.encode(page.get(page.size() - 1)) : null;
return new CursorPage<>(page.stream().map(PostDto::of).toList(), next);
}

Fetching 21 rows and returning 20 is a cheap way to know whether a next page exists without a count query. Spring Data also offers this pattern built in through Window and KeysetScrollPosition; check your version.

7Follow-up questions

How do you support a previous page link?

We reverse the comparison and the order for that query, then reverse the result back. For the page before the first row shown, we ask WHERE (created_at, id) > (:firstCreatedAt, :firstId) ORDER BY created_at ASC, id ASC LIMIT 20, which returns the 20 rows just before it in the display order, and then reverse those 20 in the application. The response carries two cursors, one for the first row and one for the last, so the client can go both ways.

Can users jump to page 3,000 with keyset pagination?

Not directly, because a cursor only knows where the previous page ended, not where page 3,000 begins. Most interfaces do not need arbitrary jumps; they need next, previous, and filters or a search to narrow the list. If a jump is required, it can be approximated by jumping to a date, which is itself a keyset position.

What if users can sort by different columns?

Each sort needs its own cursor columns, always ending with the unique id as a tie-breaker, and its own index matching the order, such as (price, id) for a price sort. The cursor should record which sort it belongs to, so a cursor from one sort is not reused with another.

8Conclusion

In this answer, we saw that OFFSET 100000 makes the database read and discard 100,000 rows to return 20, so cost grows with the page number. We rewrote the query as keyset pagination with WHERE (created_at, id) < (:lastCreatedAt, :lastId) and the matching ORDER BY, used id as a tie-breaker so no rows are skipped or repeated, and backed it with an index on (created_at DESC, id DESC) so every page is a seek plus 20 entries. We also saw that keyset pages stay stable when rows are inserted and how the cursor moves through a Spring endpoint.

What to say in the interviewAbout 100 seconds aloud

Open with

OFFSET is slow on deep pages because the database cannot jump to a row number. It has to produce the rows in order, count off the first 100,000 and discard them, and only then return 20, so page 5,000 does five thousand times the work of page 1, even with a perfect index.

Then, if they want more

With keyset pagination I remember the sort key of the last row I returned and ask for rows after it: WHERE the pair created_at, id is less than the last created_at and id, ORDER BY created_at DESC, id DESC, LIMIT 20.

The id is a tie-breaker. created_at alone is not unique, so with a page boundary inside rows that share a timestamp, less-than would skip some and less-or-equal would repeat some; adding the unique id gives every row exactly one position.

Then I add an index on created_at DESC, id DESC, and the query seeks straight to the cursor position and reads 20 entries, so page 5,000 costs the same as page 2.

It is also more correct: with OFFSET, new rows inserted at the top shift everything and the user sees duplicates on the next page, while a keyset cursor points to a key, so the next page continues exactly after the last row shown.

In the API I return an opaque encoded cursor, and I fetch 21 rows to know whether there is a next page without counting. In MySQL I would check that the row comparison uses the index or write it expanded with OR.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "Rewrite this pagination to keyset pagination and explain why it is faster on page 5,000:": https://scrivio-interview-library.netlify.app/databases/query-optimization/7176774ae7/