Quick revision
The short answer
For a paged @Query, Spring Data derives the count by rewriting our select into select count(...), keeping the joins. A join to a collection multiplies rows, so the count can report joined rows instead of distinct orders, and it also carries joins and fetches the count does not need, which makes it slow. We fix it by giving countQuery explicitly, by returning a Slice when the total is not shown, and on very large tables by accepting an estimate, since an exact count is expensive whatever we write.
What to remember
In this answer, we saw that Spring Data derives the count for a paged @Query by rewriting its select into a count and keeping every join. A join to a collection makes it count joined rows instead of distinct roots, and unneeded joins and fetches make it slow. We fixed it with an explicit countQuery using exists, avoided the count entirely with Slice when no total is shown, and used planner estimates for very large tables, where an exact count is expensive regardless.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
For a paged @Query, Spring Data derives the count by rewriting our select into select count(...), keeping the joins. A join to a collection multiplies rows, so the count can report joined rows instead of distinct orders, and it also carries joins and fetches the count does not need, which makes it slow. We fix it by giving countQuery explicitly, by returning a Slice when the total is not shown, and on very large tables by accepting an estimate, since an exact count is expensive whatever we write.
Why this question is asked
Paged screens show 'page 3 of 12' everywhere, and few people think about where the 12 comes from. In a Spring Data repository it comes from a second query that the framework writes for us, and when our main query has joins that generated count is often wrong or slow. Interviewers ask this because it is a common production surprise: correct pages, wrong totals, and a count query that takes longer than the page itself. In this answer, we will see how Spring Data builds the count, reproduce the wrong total, look at the slow case, and then go through the three fixes.
1How Spring Data Builds the Count Query
When a repository method takes a Pageable and returns Page<T>, Spring Data runs two queries: our query with an offset and limit for the rows of the page, and a count query for the total. For a derived query, one built from the method name, it generates both itself. For a @Query string, it takes our JPQL and rewrites the select clause into a count, keeping the from, joins and where clause as they are.
That rewrite is mechanical. Spring Data cannot know which joins matter for the count and which are only there to load data or filter, so it keeps them all. Newer versions parse the query properly rather than using regular expressions and handle more cases, such as turning select distinct o into count(distinct o), but the basic approach is the same, so check what your version generates.
2Reproducing the Wrong Total
Suppose order 1 has three lines for product 9 and order 2 has one. The join produces four rows, one per matching line. The page query may also return order 1 several times unless we add distinct, and the count query counts four.
| Query | Result | Correct? |
|---|---|---|
count(o) with join to lines | 4 | No: counts joined rows |
count(distinct o) with join | 2 | Yes, but sorts or hashes all ids |
count(o) where exists (line ...) | 2 | Yes, and no row multiplication |
So the screen says there are 4 results and 1 page of 20, while the list shows 2 orders. With more data the mismatch also shifts the page count, and users click through to empty last pages.
3Why the Count Can Also Be Slow
The second problem is extra work. Our page query might join customer and shipping address so it can sort by customer name or filter by region. The derived count keeps those joins even when it does not need them. Worse, a query with join fetch, which loads an association together with the entity, has no meaning in a count, because there is nothing to load. Depending on the version, Hibernate either rejects the fetch in the count query or Spring Data strips it, so check what yours does; either way, the safest path is to write the count ourselves.
Finally count(distinct ...) over a large join forces the database to collect every matching id and remove duplicates before it can answer, which on millions of rows can take longer than fetching the page.
4Fix 1: Provide countQuery Explicitly
@Query has a countQuery attribute for exactly this. We write the count that answers the real question, how many orders match, with only the joins or subqueries the filter needs.
Notice that the count uses exists rather than a join. An exists subquery stops at the first matching line for each order, so no rows multiply and no distinct is needed. The page query keeps distinct so each order appears once in the content. For native queries the attribute works the same way, with a native countQuery.
5Fix 2: Return a Slice When the Total Is Not Needed
Many interfaces only need a next button or infinite scroll, not 'page 3 of 12'. A Slice<T> return type tells Spring Data to skip the count entirely. It fetches one row more than the page size to find out whether a next page exists.
This is the cheapest fix of all, and on busy list endpoints it often halves the database load, because the count was the expensive half.
6Fix 3: Accept an Estimate on Large Tables
Even a perfect count query has to visit every matching row or index entry. In PostgreSQL, counting 50 million rows reads the whole table or a whole index, because MVCC, the way PostgreSQL keeps several versions of each row, means it cannot keep one cheap row counter. If users only need a rough idea, 'about 50 million results', we can read the planner's estimate instead.
Search engines and large admin screens do this routinely: an exact count up to a cap, such as 10,000, and 'more than 10,000' beyond it. That keeps the user experience honest without paying for a full count on every request.
7Follow-up questions
Does adding distinct to the main query fix the derived count?
Often, yes. Spring Data turns select distinct o into count(distinct o), which gives the right number. But count distinct over a large join is expensive, so for hot queries an explicit countQuery with exists is usually both correct and faster.
When does Spring Data skip the count for a Page?
It skips it when the total can be worked out from the content, for example when the first page returns fewer rows than the page size, or on the last page. In every other case it runs the count, which is why a Slice is the better choice when no total is displayed.
Can a join fetch query be paged at all?
Fetching a collection and paging at the same time makes Hibernate page in memory, with warning HHH90003004, because a row limit would cut an order's lines. The usual fix is to page the ids first and fetch the collections in a second query, and to give that paged query its own simple countQuery.
8Conclusion
In this answer, we saw that Spring Data derives the count for a paged @Query by rewriting its select into a count and keeping every join. A join to a collection makes it count joined rows instead of distinct roots, and unneeded joins and fetches make it slow. We fixed it with an explicit countQuery using exists, avoided the count entirely with Slice when no total is shown, and used planner estimates for very large tables, where an exact count is expensive regardless.
Open with
When a @Query with a Pageable returns a Page, Spring Data runs a second query for the total, and for a query string it builds that count by rewriting the select into count and keeping the rest.
Then, if they want more
If my query joins a collection, say orders join lines, every matching line produces a row, so the count can say 4 when only 2 orders match, and the page count is wrong.
It also keeps joins the count does not need, and fetch joins make no sense in a count at all, so it can be slow or fail depending on the version. My first fix is to write countQuery explicitly, counting the root entity with an exists subquery for the collection filter, so nothing multiplies and no distinct is needed.
My second fix is to ask whether the total is needed at all: if the screen only has a next button, I return a Slice, which skips the count and fetches one extra row to know if there is more.
And for very large tables I remind the team that an exact count is expensive no matter how it is written, because PostgreSQL has to visit every row, so we can show an estimate from the planner statistics or cap the exact count.
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.
- Official documentation
- Spring Data JPA reference, Hibernate ORM documentation, Spring Framework reference, Transaction management
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 "Why can the count query that Spring Data derives for a paged @Query with joins give...": https://scrivio-interview-library.netlify.app/databases/jpa-queries/a37b5000ae/