Scrivio Interview library
CodingFoundations6 min read · updated 12 November 2026

Write a Spring Data JPA method that returns the second page of 20 orders for a customer, newest first, including a stable tiebreaker.

We declare Page<Order> findByCustomerId(Long customerId, Pageable pageable) and call it with PageRequest.of(1, 20, Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id"))). Page numbers are zero-based, so page 1 is the second page; the id tiebreaker makes the order deterministic when two orders share a timestamp, and an index on (customer_id, created_at, id) lets the database read the page in order instead of sorting.

Why this question is asked

Paging through a customer's orders is one of the first things every web application needs, and it hides two classic bugs: off-by-one page numbers and rows that appear twice or not at all as the user moves between pages. Interviewers ask this question to see whether we know Spring Data's paging API and also understand what SQL it produces and why ordering must be unique. In this answer, we will write the repository method, call it for the second page, look at the SQL and the count query, see why the tiebreaker matters, and finish with the index that makes it fast.

1A Quick Recap of Paging in Spring Data

Spring Data JPA can page any query method that takes a Pageable parameter. A Pageable carries three things: the page number, the page size and the sort order. PageRequest is the standard implementation we create with PageRequest.of(page, size, sort).

The return type decides how much work happens. A Page<T> contains the rows of the page and also the total number of elements and pages, which needs an extra count query. A Slice<T> only knows whether there is a next page, and a List<T> just returns the rows.

2Writing the Repository Method

A derived query, one Spring Data builds from the method name, is enough here. findByCustomerId becomes where o.customer.id = ?1 if Order has a customer association, or where o.customerId = ?1 if it has a plain customerId field.

Java
public interface OrderRepository extends JpaRepository<Order, Long> {
Page<Order> findByCustomerId(Long customerId, Pageable pageable);
}
Pageable second = PageRequest.of(1, 20,
Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id")));
Page<Order> page = orders.findByCustomerId(42L, second);
page.getNumber(); // 1: zero-based, so this is the second page
page.getContent().size(); // 20 (fewer on the last page)
page.getTotalElements(); // 57: from the count query
page.getTotalPages(); // 3

Notice that the sort uses entity property names, createdAt and id, not column names. Spring Data turns them into an order by clause. If we misspell a property, Spring Data fails when the query runs, with a PropertyReferenceException.

3Why Page 1 Is the Second Page

Spring Data numbers pages from zero. PageRequest.of(0, 20) is the first page, rows 1 to 20, and PageRequest.of(1, 20) is the second, rows 21 to 40. Hibernate turns this into an offset of page times size, so offset 20 and limit 20.

This trips people up at the web layer, where users and URLs often count from one. Spring Data web support can accept one-based page numbers with spring.data.web.pageable.one-indexed-parameters=true, but inside the service layer we should keep the zero-based meaning to avoid confusion.

SQL
-- SQL for the second page (PostgreSQL)
select o.* from orders o
where o.customer_id = ? -- 42
order by o.created_at desc, o.id desc
offset ? rows fetch first ? rows only; -- offset 20, fetch 20 (exact syntax depends on dialect)
select count(o.id) from orders o where o.customer_id = ?; -- 57, because we asked for a Page

4Why We Need a Tiebreaker

An order by clause only guarantees an order for rows whose sort values differ. If three orders were created in the same millisecond, the database may return them in any order, and it may choose a different order on the next query, for example after a plan change or a parallel scan.

With offset paging that causes real bugs. Suppose orders 101, 102 and 103 share a timestamp and straddle the boundary between page 1 and page 2. Page 1 might end with 101 and 102, and page 2, queried separately, might start with 101 again. The user sees 101 twice and never sees 103. Adding id as a second sort key makes every row's position unique, because ids never repeat, so each page is the same every time we ask.

Rows at the page boundary
Positioncreated_atWithout tiebreakerWith id desc
20 (end of page 1)10:00:00.000101 on one run, 103 on the next103
21 (start of page 2)10:00:00.000may repeat 101102
2210:00:00.000103 may be skipped101
Three orders share a timestamp. Only a unique sort makes the boundary stable.

5The Index That Supports the Query

Without a suitable index, the database must find all of the customer's orders, sort them, and throw away the first 20. An index on (customer_id, created_at, id) stores entries already grouped by customer and ordered by time and id. The database jumps to customer 42, walks the index backwards for the descending order, skips 20 entries and reads 20, with no sort step at all.

SQL
create index orders_customer_created_id on orders (customer_id, created_at, id);
-- B-tree indexes can be scanned in both directions, so this also serves
-- order by created_at desc, id desc for one customer.

The column order matters: the equality column, customer_id, comes first, then the sort columns in the same order as the order by. An index on (created_at, customer_id) would not help nearly as much.

6When Offset Paging Gets Slow

Offset paging has a cost that grows with the page number, because the database still reads and discards all skipped rows. For a customer with 50 orders this is irrelevant. For an admin screen over millions of rows, page 5,000 means skipping 100,000 rows. Two fixes help. If we do not need the total, returning Slice<Order> drops the count query. For deep scrolling, keyset paging, also called seek paging, asks for rows after the last one seen, where (created_at, id) < (:lastCreatedAt, :lastId), which uses the same index and costs the same on every page. Spring Data supports this with its scrolling API and KeysetScrollPosition in recent versions.

7Follow-up questions

Why not sort by id alone, since ids grow over time?

Often ids do follow insertion order, but not always: sequences can be cached per node, ids can come from another system, and createdAt may be set from the business event time rather than the insert time. Sorting by the field we actually mean, then by id as a tiebreaker, is correct regardless of how ids are generated.

Can we put the sort in the method name instead?

Yes, findByCustomerIdOrderByCreatedAtDescIdDesc(Long customerId, Pageable pageable) fixes the order in the name, and the Pageable then only carries page and size. Passing the Sort in the Pageable is more flexible when the client can choose the sort, but then we must whitelist the allowed properties.

Does the count query run for every page?

Yes, for a Page return type Spring Data runs a count query alongside the content query, except when it can work out the total from the content itself, such as on the last page with fewer rows than the page size. If the total is not shown, a Slice avoids it.

8Conclusion

In this answer, we wrote a derived query that returns Page<Order> for a customer, and called it with PageRequest.of(1, 20) sorted by createdAt descending and then id descending. We saw that page numbers start at zero, what SQL and count query Hibernate produces, why the id tiebreaker keeps page boundaries stable when timestamps repeat, and how an index on (customer_id, created_at, id) lets the database return the page without sorting.

What to say in the interviewAbout 70 seconds aloud

Open with

I would declare Page<Order> findByCustomerId(Long customerId, Pageable pageable) on the repository and call it with PageRequest.of(1, 20, Sort.by(Sort.Order.desc("createdAt"), Sort.Order.desc("id"))). Spring Data pages are zero-based, so page 1 is the second page, which becomes offset 20 and limit 20 in SQL.

Then, if they want more

Because the return type is Page, Spring Data also runs a count query so it can report the total elements and pages; if the UI only needs a next button, I would return a Slice to skip that. The id in the sort is a tiebreaker.

Ordering by createdAt alone is not deterministic when two orders share a timestamp, so rows at a page boundary can show up twice or be skipped as the user moves between pages. Since ids are unique, adding id desc makes every position fixed.

To make it fast I would add an index on customer_id, created_at, id, in that order, so the database can jump to the customer and read the rows already in order, scanning backwards for the descending sort, with no sort step. For very deep pages I would consider keyset paging instead of offsets.

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 "Write a Spring Data JPA method that returns the second page of 20 orders for a customer...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/3696da60d6/