Video in progress

Strong Middle 🌱 Spring

When you use a native @Query with Pageable, how is the total count query produced, and when do you write the countQuery yourself?

Spring Data tries to derive the count query from the native query itself, but with JOIN, GROUP BY, DISTINCT or a CTE it comes out wrong or slow. In those cases you write countQuery explicitly, and if you don't need the total count, you return a Slice.

📖 Answer

@Query(value = """
        select o.* from orders o
        join customer c on c.id = o.customer_id
        where c.region = :region and o.status = 'PAID'
        """,
       countQuery = """
        select count(*) from orders o
        join customer c on c.id = o.customer_id
        where c.region = :region and o.status = 'PAID'
        """,
       nativeQuery = true)
Page<Order> findPaidByRegion(@Param("region") String region, Pageable pageable);

When a Page is returned, Spring Data sends two queries: one for the data with LIMIT/OFFSET, and a count for the total. In JPQL it derives the count reliably. In native SQL it parses the string and replaces it with select count(...). In complex SQL this sometimes produces broken SQL, and sometimes it works but is slow because of unneeded JOINs and sorting.

When you write it yourself:

  • there is a GROUP BY, DISTINCT, WITH (CTE) or UNION;
  • the count doesn't need the JOIN: counting just by orders is enough;
  • you've seen in the log that the count query is slower than the main query.

The second question: do you need the total count at all? In a "load more" feed in a mobile app you don't. If you return Slice<Order>, no count is sent: Spring asks for one extra row and knows whether there's a next page. On a table with a million rows this is a noticeable saving.

Also watch sorting in a native query: the sort names in Pageable are added to the SQL almost unchanged, meaning a column name is expected, not an entity field. Validate the sort field that comes from the client against an allowlist.