Video in progress

Why is a query that returns a `Page` slow in Spring Data JPA, and how do you manage the count query?

Page sends two queries every time: one for the data and one for count(*). On a big table or a query with complex joins, the count can be more expensive than the data query. The fix is to write the countQuery separately and keep it simple, or to return a Slice if you don't need the total.

📖 Answer

Page<Order> findByStatus(Status status, Pageable pageable);

When this method is called, Spring Data sends two queries, roughly like this:

select ... from orders where status = ? order by created_at desc limit 20 offset 40;
select count(o.id) from orders o where o.status = ?;

The first runs fast on an index: once it finds 20 rows, it stops. The second has to count every row that matches the condition. On PostgreSQL with a 30-million-row table, that can take several seconds.

If you write a join fetch in @Query, Spring Data tries to derive the count query itself and sometimes produces wrong SQL. In that case, provide the count by hand:

@Query(value = "select o from Order o join fetch o.customer where o.status = :s",
       countQuery = "select count(o) from Order o where o.status = :s")
Page<Order> findPage(@Param("s") Status s, Pageable pageable);

Ask whether the UI really needs a "1,234,567 records total" label. Often "is there a next page?" is enough. In that case return Slice<Order>: Spring Data requests limit + 1 rows and never sends a count at all.

Another option is an approximate count. On PostgreSQL, an estimate from pg_class.reltuples or from the EXPLAIN output is good enough for admin panels.

On deep pages (offset 100000) the data query slows down too. There you need to move to keyset pagination, but that's a separate topic.