Quick revision
The short answer
Run the generated SQL with EXPLAIN ANALYZE: the subquery shows loops = 5,000, and each loop reads many order rows, or scans the table, because there is no index that answers 'latest order for this customer' directly. An index on orders(customer_id, created_at DESC) turns each loop into a probe of one index entry. Alternatively, rewrite the query as a join to a grouped derived table of MAX(created_at) per customer or, in PostgreSQL, a LATERAL subquery with LIMIT 1; paginate the page so far fewer rows are computed; and if the screen is very hot, keep last_order_at on customers.
What to remember
In this answer, we captured the SQL from Spring Data JPA, ran EXPLAIN ANALYZE, and found the correlated subquery running 5,000 times, each reading hundreds of orders. An index on orders(customer_id, created_at DESC) made each loop a single-entry probe. We also saw two rewrites, a grouped derived table and LATERAL with LIMIT 1, how pagination reduces the number of loops, and when denormalising last_order_at onto customers is worth its write cost.
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.
Run the generated SQL with EXPLAIN ANALYZE: the subquery shows loops = 5,000, and each loop reads many order rows, or scans the table, because there is no index that answers 'latest order for this customer' directly. An index on orders(customer_id, created_at DESC) turns each loop into a probe of one index entry. Alternatively, rewrite the query as a join to a grouped derived table of MAX(created_at) per customer or, in PostgreSQL, a LATERAL subquery with LIMIT 1; paginate the page so far fewer rows are computed; and if the screen is very hot, keep last_order_at on customers.
Why this question is asked
List pages are where small query decisions become visible to users. A customer list with a 'last order' column looks harmless, and with 50 test customers it loads instantly. With 5,000 real customers it takes 8 seconds, and the team starts talking about caching. Interviewers ask this scenario because the diagnosis is concrete and teachable: get the SQL, read the plan, find the per-row work, and remove it. In this answer, we will capture the query from Spring Data JPA, read its plan, fix it with an index, compare two rewrites, and then reduce the work with pagination and, if needed, denormalisation.
1Getting the Real SQL and Its Plan
The repository method probably looks like the one below. The subquery in the select list is correlated: it refers to c, the outer customer, so logically it runs once for every customer row.
First, we need the SQL that Hibernate actually sends. Setting logging.level.org.hibernate.SQL=debug prints it, or we can find it in pg_stat_statements. Then we run it in psql with EXPLAIN (ANALYZE, BUFFERS) and the real data. EXPLAIN ANALYZE executes the query and reports actual rows, times and loops for every node, which is what we need to see per-row work.
2Reading the Plan: 5,000 Loops
The plan has the customer scan at the top and the subquery as a SubPlan underneath. The number to look at is loops on the SubPlan's nodes: it runs once per customer.
So each of the 5,000 executions uses an index on customer_id only. It finds all of that customer's orders, about 410 on average, fetches each row from the table to read created_at, and computes the maximum. That is about 2 million row fetches, many of them random reads from disk, to produce 5,000 dates. At roughly 1.6 ms per loop, the total is 8 seconds. Notice that the query is not wrong and no single loop is slow; the cost is the loop count times the work per loop.
3Fix 1: An Index That Answers the Question
The subquery asks for the largest created_at of one customer. A composite index on (customer_id, created_at DESC) stores each customer's orders already sorted by date, so the maximum is the first entry for that customer. PostgreSQL rewrites MAX over an indexed column into a one-row index lookup, so each loop reads one entry instead of 410 rows.
The loops are still 5,000, but each loop is now a few buffer reads, usually from memory, and the page drops from 8 seconds to tens of milliseconds. The index is an index-only scan because both columns it needs are in the index. This is often the whole fix, and it is the cheapest, because no application code changes. The old single-column index on customer_id becomes redundant, since the new index starts with the same column, and can be dropped later to save write cost.
4Fix 2: Rewriting the Query
Sometimes we cannot add an index, or we want a plan that does not depend on one probe per row. Two rewrites help. The first computes all the maximums once, in a grouped derived table, and joins them to customers. The second, in PostgreSQL, uses LATERAL, a subquery in FROM that can refer to the outer row and return a whole row, here the latest order.
| Option | Work per page of 5,000 | Needs |
|---|---|---|
| Original subquery, customer_id index | About 2,000,000 row fetches | Nothing; 8 s |
| Subquery + (customer_id, created_at DESC) | 5,000 one-entry probes | New index; tens of ms |
| Grouped derived table | One pass over orders | Nothing; good for all customers |
| LATERAL ... LIMIT 1 | 5,000 probes, extra columns | Same index, native query |
| Paginate to 50 rows | 50 probes | UI change |
| Stored last_order_at | No orders access | Write-path update |
The grouped version reads all of orders once, about 2 million rows here, and aggregates them, which is a good plan when we need every customer and have no composite index. The LATERAL version is the correlated lookup written explicitly, and it shines with the composite index, especially because it can also return other columns of the latest order, such as its total, which the scalar subquery cannot. Both use LEFT JOIN so customers without orders still appear, with NULL. In Spring Data we would put either into a native @Query with an interface or record projection.
5Doing Less Work: Pagination and Denormalisation
A list page showing 5,000 rows at once is rarely what users need. With pagination, the outer query returns, say, 50 customers per page, and the correlated subquery runs 50 times instead of 5,000. In Spring Data that is a Pageable parameter. For large tables, keyset pagination, where the next page starts after the last name and id seen, is better than OFFSET, which still reads and discards all earlier rows. A Page return type also triggers a count query, so a Slice may be enough if the page only needs a 'next' link.
If this screen is very hot, opened thousands of times a minute, we can go one step further and store last_order_at on customers, updated in the same transaction that creates an order. The list becomes a read of one table with no orders access at all. The cost is that every write path that creates orders must update it, so I would only do this after the index and pagination, and only if measurements still show a need.
6Follow-up questions
Why does PostgreSQL turn MAX into a LIMIT 1 lookup?
Because the largest value of an indexed column is the first entry when reading the index in the right direction. The planner recognises MIN and MAX over a column that leads an index, after any equality conditions such as customer_id = c.id, and replaces the aggregate with an index scan that stops after one row, skipping NULLs. That optimisation only applies when the index matches, which is why the composite index makes such a difference.
Would fetching customers and orders in two queries from Java be better?
It can work: load the page of customers, then one query for the maximum per customer with WHERE customer_id IN (the ids) GROUP BY customer_id, and merge in a map. That is two round trips and stays fast with pagination. What we must avoid is one query per customer from Java, the N+1 problem, which is the same per-row cost as the correlated subquery plus a network round trip each time.
How do you stop this coming back?
We keep the EXPLAIN output in the pull request that fixed it, add a test that runs the query on a realistic data set with Testcontainers and checks its time or buffers stay within a budget, and watch mean execution time for this query in pg_stat_statements. Setting a slow-query log threshold, for example log_min_duration_statement at 500 ms, also makes regressions visible quickly.
7Conclusion
In this answer, we captured the SQL from Spring Data JPA, ran EXPLAIN ANALYZE, and found the correlated subquery running 5,000 times, each reading hundreds of orders. An index on orders(customer_id, created_at DESC) made each loop a single-entry probe. We also saw two rewrites, a grouped derived table and LATERAL with LIMIT 1, how pagination reduces the number of loops, and when denormalising last_order_at onto customers is worth its write cost.
Open with
First I would get the actual SQL Hibernate sends, from the SQL log or pg_stat_statements, and run it with EXPLAIN ANALYZE and BUFFERS on production-like data. I expect to see the subquery as a SubPlan with loops equal to 5,000, one per customer, and inside each loop an index scan on customer_id that reads all of that customer's orders, a few hundred rows, to find the maximum date.
Then, if they want more
The total is millions of row fetches for 5,000 dates, which is where the 8 seconds go. The simplest fix is a composite index on orders customer_id, created_at descending. Then PostgreSQL turns MAX into a one-row index-only lookup, each loop is a few buffer reads, and the page drops to milliseconds without touching the code.
If an index is not an option, I would rewrite it, either as a left join to a derived table that groups orders by customer with MAX, which is one pass over orders, or, in PostgreSQL, a LEFT JOIN LATERAL with ORDER BY created_at DESC LIMIT 1, which also lets me show other columns of the latest order.
I would also paginate: 50 rows per page means 50 lookups, not 5,000, ideally keyset pagination and a Slice to avoid the count query. Only if the screen is very hot would I store last_order_at on customers and update it when an order is created.
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
- PostgreSQL documentation, The SQL Language
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 query for a list page uses a correlated subquery in the select list to...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/64cc64d4f3/