Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A Spring Data JPA endpoint returning Page<Order> is slow, and the logs show a SELECT COUNT(*) taking most of the time. How do you fix it?

A method that returns Page<Order> makes Spring Data run a second query, a COUNT, on every request to fill in the total number of elements and pages. If the screen does not need totals, we return Slice<Order>, which fetches one row more than the page size to know whether a next page exists, or Window<Order> with keyset scrolling in Spring Data 3.1 and later. If a total is needed, we give @Query a cheap countQuery without joins or fetches, or cache the count, and in every case we check that the count uses an index that matches the filter.

Why this question is asked

Paginated list endpoints are some of the most common in any Spring application, and Page is what most tutorials show, so this problem appears in many codebases once tables grow. The fix is usually small, but it requires knowing what Page does behind the scenes and what the screen actually uses. Interviewers ask it because it combines Spring Data knowledge with database cost. In this answer, we will see why Page counts, replace it with Slice or Window when totals are not needed, write a cheaper count when they are, and make sure the count itself is fast.

1Why Page Runs a Count

A Page in Spring Data holds the rows of one page and also the total number of elements and total number of pages, so a UI can show 'page 3 of 4,812'. Spring Data cannot know the total without asking the database, so for each call it runs two queries: one for the content with LIMIT and OFFSET, and one COUNT derived from the same condition.

Java
Page<Order> findByStatus(Status status, Pageable pageable);
orderRepository.findByStatus(Status.OPEN, PageRequest.of(2, 20));
// select ... from orders o where o.status=? order by ... offset 40 rows fetch first 20 rows only -- 4 ms
// select count(o.id) from orders o where o.status=? -- 1,900 ms

Notice the timings. The content query reads 60 rows through an index; the count must visit every open order to count it, which on a large table is most of the cost. Spring Data skips the count only when it can compute the total without it, for example on the first page when fewer rows than the page size come back. For every other request, the count runs again, even though the total rarely changes between two clicks.

2Fix 1: Return a Slice When Totals Are Not Needed

Many screens only need 'is there a next page?', such as infinite scroll or a simple Next button. A Slice answers exactly that. Spring Data asks for one row more than the page size: if 21 rows come back for a page of 20, there is a next page, and it returns the first 20.

Java
Slice<Order> findByStatus(Status status, Pageable pageable);
Slice<Order> s = orderRepository.findByStatus(Status.OPEN, PageRequest.of(2, 20));
// select ... where o.status=? order by ... offset 40 rows fetch first 21 rows only -- one query, 4 ms
s.hasNext(); // true
s.getContent(); // 20 orders

The count query is gone completely. The API contract changes, since the response no longer carries totalElements, so we agree that with the front end first. Notice that OFFSET still reads and skips all earlier rows, so deep pages stay slow; that is what the next fix addresses.

3Fix 2: Window and Keyset Scrolling

Since Spring Data 3.1, repositories can return a Window, using a ScrollPosition instead of a page number. With keyset scrolling, the next request starts after the last row seen, WHERE id > :lastId, instead of skipping rows with OFFSET, so every page costs the same however deep the user scrolls.

Java
Window<Order> findFirst20ByStatusOrderByIdAsc(Status status, ScrollPosition position);
Window<Order> w = repo.findFirst20ByStatusOrderByIdAsc(Status.OPEN, ScrollPosition.keyset());
// where status=? order by id fetch first 21 rows only
Window<Order> next = repo.findFirst20ByStatusOrderByIdAsc(Status.OPEN, w.positionAt(w.size() - 1));
// where status=? and id>? order by id fetch first 21 rows only -- same cost on page 1 or page 10,000
Choosing the return type
Return typeQueries per requestTotalsDeep pages
Page<Order>content + COUNTyesslow (OFFSET)
Slice<Order>content only (size + 1)no, only hasNextslow (OFFSET)
Window<Order> keysetcontent only (size + 1)nofast, constant cost

Keyset scrolling needs a stable, unique sort order, here id, or a sort column plus id as a tie-breaker, and it cannot jump to an arbitrary page number. For feeds, exports and API clients that walk all records, those limits do not matter and the gain is large.

4Fix 3: A Cheaper Count When a Total Is Required

Sometimes the total is a real requirement, such as an admin screen that shows 'page 3 of 50'. Then we make the count as cheap as possible. The derived count copies the content query's joins, and with a join fetch it may be wrong or slow. With @Query we can give a separate countQuery that only touches what the count needs.

Java
@Query(value = "select o from Order o join fetch o.customer where o.status = :status",
countQuery = "select count(o) from Order o where o.status = :status")
Page<Order> findOpenWithCustomer(Status status, Pageable pageable);
// count: select count(o.id) from orders o where o.status=? -- no join to customers

If the total does not need to be exact to the second, caching it for a minute per filter, for example with @Cacheable on a separate count method and building the page with PageImpl, turns thousands of counts into one per minute. Another option is to show an estimate or a capped count such as '1,000+' when the real number is large.

5Make the Count Use an Index

Whatever count remains must be efficient. We run EXPLAIN ANALYZE on the exact count SQL from the logs and check that it uses an index matching the filter, here on status, ideally a small one that allows an index-only scan. A partial index such as CREATE INDEX ON orders (id) WHERE status = 'OPEN' makes counting open orders very cheap if the open set is small. If the plan shows a sequential scan over the whole table, no change on the Spring side will save it.

6Follow-up questions

Why can Spring Data sometimes skip the count with Page?

If the requested page is the first page and the query returns fewer rows than the page size, the total is simply the number of rows returned, so Spring Data does not need to count. The same reasoning applies to the last page, when the offset plus the rows returned gives the total.

Does a join fetch break pagination?

A join fetch on a collection with pagination makes Hibernate apply the limit in memory after loading all rows, with a warning in the log, which is both slow and memory-hungry. Fetch to-one associations with join fetch, and load collections with a second query or batch fetching.

How do you keep the API backward compatible when removing totals?

Add a new endpoint or parameter that returns a slice or cursor response, migrate clients, and then retire the totals version. Many teams keep an optional includeTotal flag for the few screens that truly need it.

7Conclusion

In this answer, we saw that returning Page makes Spring Data run a count query for every request, which on a large table can cost far more than the page itself. When totals are not needed, Slice fetches size plus one row and skips the count, and Window with keyset scrolling also removes the cost of deep pages. When a total is required, a separate countQuery without joins or fetches, caching or an approximate count keeps it cheap, and the count should always use an index that matches the filter.

What to say in the interviewAbout 90 seconds aloud

Open with

The cause is the Page return type. To fill totalElements and totalPages, Spring Data runs a second query, a COUNT with the same condition, on every request, and on a large table that count visits every matching row while the page itself reads only twenty.

Then, if they want more

First I would check whether the screen really needs totals. If it only needs a next button or infinite scroll, I return Slice, which asks for page size plus one row and uses the extra row to answer hasNext, so the count disappears.

If clients scroll deep or walk all records, I would use Window with a keyset ScrollPosition, available since Spring Data 3.1, so each page starts after the last id seen instead of using OFFSET, and every page costs the same.

If a total is a real requirement, I write the count myself with countQuery in @Query, without the join fetches and joins the content query has, and I consider caching it for a minute or showing an approximate number.

Finally I would take the count SQL from the logs, run EXPLAIN ANALYZE on it, and make sure it uses an index on the filtered column, possibly a partial index, because if the count is a full table scan nothing at the Spring layer will make it fast.

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 "A Spring Data JPA endpoint returning Page<Order> is slow, and the logs show a SELECT...": https://scrivio-interview-library.netlify.app/databases/query-optimization/ba8d8bebe3/