Scrivio Interview library
DebuggingIntermediate6 min read · updated 12 November 2026

Users report that paging through a list of orders sorted by status sometimes shows the same order on two pages and skips others. The query is ORDER BY status LIMIT 20 OFFSET :offset. What is the cause and the fix?

Many orders share the same status, and SQL defines no order among rows that tie on the ORDER BY columns, so the database may return them in a different order for each query and page boundaries cut through them differently. The fix is to add a unique tiebreaker, ORDER BY status, id, backed by an index. Concurrent inserts and status changes can still shift rows under offset pagination, and keyset pagination on (status, id) removes that problem as well.

Why this question is asked

This bug is hard to see in development because small test tables usually come back in the same order every time. In production, with thousands of orders and a planner that chooses different strategies for different queries, users see duplicates and gaps when they click through pages. Interviewers ask it as a debugging question because the fix is one column, but the reasoning reveals whether a candidate knows what SQL actually guarantees. In this answer, we will recap what ORDER BY promises, reproduce the problem, see why the database behaves this way, fix it with a tiebreaker, and then handle concurrent changes with keyset pagination.

1A Quick Recap of What ORDER BY Promises

ORDER BY guarantees only the order of rows whose sort values differ. If two rows have the same value in every ORDER BY column, the SQL standard says nothing about which comes first, and databases take that freedom seriously. A sort is called stable when equal elements keep a fixed relative order; SQL sorts are not required to be stable, and their order can depend on the query plan, the physical position of rows and even the LIMIT value.

Offset pagination takes rows 1 to 20 for page 1 (OFFSET 0), rows 21 to 40 for page 2 (OFFSET 20), and so on, with a separate query for each page. It only produces a clean sequence if every one of those queries orders the rows exactly the same way.

2Reproducing the Problem

Suppose 50 orders have status PAID. Each page request is a separate query, so each one sorts the 50 tied rows independently.

SQL
-- Page 1
SELECT id, status FROM orders ORDER BY status LIMIT 20 OFFSET 0;
-- ... 1017 PAID, 1003 PAID, 1042 PAID ... (20 rows)
-- Page 2
SELECT id, status FROM orders ORDER BY status LIMIT 20 OFFSET 20;
-- ... 1042 PAID, 1088 PAID, 1011 PAID ... (1042 appears again; 1009 never appears on any page)

Notice that the query is correct and the database is correct. Order 1042 was among the first 20 tied rows in one sort and among the next 20 in another sort, and some other row fell into the gap. Nothing is wrong with the data; the order of ties simply was not defined.

3Why the Database Returns Ties Differently

There are several ordinary reasons. With LIMIT, PostgreSQL often uses a top-N heap sort that keeps only the best N rows in memory; for OFFSET 0 LIMIT 20 it keeps 20 rows, for OFFSET 20 LIMIT 20 it keeps 40, and the two heaps can resolve ties differently. A parallel scan returns rows in whatever order the workers finish. An index scan on status returns rows in index order, while a sequential scan returns them in physical order, and the planner may switch between them as statistics change. Updates move rows physically, which changes the order of a sequential scan.

So every page query is free to place tied rows differently, and offset pagination silently assumes that it will not.

Two page queries sorting the same tied rows
PositionSort for page 1 querySort for page 2 query
191003 PAID1003 PAID
201042 PAID1009 PAID
211009 PAID1042 PAID
221088 PAID1088 PAID
Page 1 takes positions 1-20 from the first sort, page 2 takes 21-40 from the second: 1042 appears twice and 1009 never.

4Fix: Add a Unique Tiebreaker

The fix is to make the order total, meaning no two rows can tie. We add a column that is unique, usually the primary key, as the last ORDER BY column. A matching index lets the database read rows already in that order instead of sorting.

SQL
SELECT id, status FROM orders ORDER BY status, id LIMIT 20 OFFSET 20;
CREATE INDEX orders_status_id_idx ON orders (status, id);
// Spring Data: always append the id to the client's sort
Sort sort = pageable.getSort().and(Sort.by("id"));
Pageable stable = PageRequest.of(pageable.getPageNumber(), pageable.getPageSize(), sort);

Now every query, whatever plan it uses, must place order 1003 before 1009 before 1042, because their ids differ. In a Spring API it is worth adding the tiebreaker centrally, in a shared resolver or base repository method, so no endpoint forgets it.

5But Rows Still Move: Concurrent Changes

The tiebreaker fixes the duplicates caused by ties, but offset pagination has a second weakness. Between the user loading page 1 and page 2, other transactions change the data. If a new PAID order is inserted that sorts before the user's position, every later row shifts down by one, and the last row of page 1 appears again at the top of page 2. If an order on page 1 changes status from NEW to SHIPPED, it moves elsewhere in the sort, and a row the user has not seen moves up into page 1's range and is skipped.

6Keyset Pagination on (status, id)

Keyset pagination fixes this by remembering where the user stopped instead of how many rows to skip. The client sends the sort values of the last row it saw, and the next page starts strictly after them.

SQL
-- first page
SELECT id, status FROM orders ORDER BY status, id LIMIT 20;
-- last row: ('PAID', 1042)
-- next page: start after the last row seen
SELECT id, status FROM orders
WHERE (status, id) > ('PAID', 1042)
ORDER BY status, id LIMIT 20;
Step throughDiagnosing duplicates across pages
  1. Is the ORDER BY unique?
    YesLook at concurrent writesNoAdd the primary key as tiebreaker
  2. Do rows change or arrive while paging?
    YesSwitch to keyset on (status, id)NoOffset with tiebreaker is enough

2 steps in order. Play them, or step through them one at a time.

Inserts before the user's position no longer shift the next page, because the next page is defined by a value, not a count. A row whose own status changes can still jump to another part of the list, ahead of or behind the user, but rows are no longer repeated or skipped merely because other rows were inserted or deleted earlier in the list, and the index on (status, id) makes each page cost the same regardless of how deep the user goes.

7Follow-up questions

Why did the bug not appear in tests?

Small test tables are read with a simple sequential scan, which returns rows in insertion order every time, so ties come back in a consistent order by accident. In production, larger tables, different plans, parallel workers and top-N sorts break that accident. A good test sorts by a non-unique column with many ties and checks that the pages together contain each row exactly once.

Does the tiebreaker have to be the primary key?

It has to be unique and immutable, so a row's position cannot change by itself. The primary key is the natural choice. A created_at timestamp is not enough on its own, because two rows can share a timestamp.

Is ORDER BY status, id slower than ORDER BY status?

With an index on (status, id), it is usually faster, because the database can read rows in order and stop after the page, instead of sorting every row with that status.

8Conclusion

In this answer, we traced duplicate and missing orders to a non-unique sort: SQL does not define the order of ties, and separate page queries may resolve them differently because of top-N sorts, parallel scans and plan changes. Adding the primary key as a tiebreaker, with an index on (status, id), makes the order total. Concurrent inserts and status changes still shift rows under offset pagination, and keyset pagination on (status, id) gives stable pages under concurrent writes.

What to say in the interviewAbout 80 seconds aloud

Open with

The cause is that status is not unique. SQL only guarantees the order of rows whose sort values differ; among rows with the same status there is no defined order, and each page is a separate query.

Then, if they want more

So the page 1 query and the page 2 query may sort the tied PAID orders differently, for example because PostgreSQL uses a top-N heap sort whose size depends on offset plus limit, or because the plan switches between an index scan, a sequential scan or a parallel scan.

Then an order that was in the first 20 in one sort is in the next 20 in another, so it shows up twice and something else is skipped.

The fix is to make the order total by adding a unique tiebreaker, ORDER BY status, id, with an index on status and id, and in Spring I would append the id to every client sort centrally. There is also a second issue: with offset pagination, inserts and status changes between page requests shift rows across page boundaries.

If that matters, I would move to keyset pagination, where the next page is WHERE status, id greater than the last row's values, which stays stable under concurrent writes.

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 "Users report that paging through a list of orders sorted by status sometimes shows the...": https://scrivio-interview-library.netlify.app/spring-boot/rest-api-design/22cb52bd49/