Quick revision
The short answer
A correlated subquery in the select list can only return one value, while LATERAL (CROSS APPLY in SQL Server) lets a subquery in FROM refer to the outer row and return several rows and columns for it. That makes it the natural tool for top-N per group: CROSS JOIN LATERAL (SELECT ... WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 3). With an index on (customer_id, created_at DESC), each probe reads only N index entries, which is ideal when groups are large or we only need some groups. A ROW_NUMBER() window over the whole table reads every row and is better when groups are small or we need every group.
What to remember
In this answer, we saw that a correlated subquery in the select list can return only one value, while LATERAL or CROSS APPLY lets a subquery in FROM use the outer row and return many rows and columns. For top-N per group, LATERAL with ORDER BY and LIMIT over an index on (customer_id, created_at DESC) reads only N entries per group, which wins when groups are large or only some are needed, while ROW_NUMBER reads every row and wins when groups are small and all are needed. MySQL supports LATERAL from 8.0.14.
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.
A correlated subquery in the select list can only return one value, while LATERAL (CROSS APPLY in SQL Server) lets a subquery in FROM refer to the outer row and return several rows and columns for it. That makes it the natural tool for top-N per group: CROSS JOIN LATERAL (SELECT ... WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 3). With an index on (customer_id, created_at DESC), each probe reads only N index entries, which is ideal when groups are large or we only need some groups. A ROW_NUMBER() window over the whole table reads every row and is better when groups are small or we need every group.
Why this question is asked
'The three latest orders per customer', 'the top five products per category', 'the last login per user': top-N per group is one of the most common query shapes, and the obvious ways to write it are either awkward or slow. LATERAL is the feature that makes it simple and fast in the right cases. Interviewers ask about it at senior level to see whether we know what it adds over correlated subqueries and, more importantly, when it beats the window function approach and when it does not. In this answer, we will recap the limits of a correlated subquery, see what LATERAL adds, write top-N both ways, and compare their costs with concrete numbers.
1A Quick Recap: What a Correlated Subquery Cannot Do
A correlated subquery refers to columns of the outer row. In the select list it must be scalar: it returns at most one row with one column, such as the date of a customer's latest order. If we want the latest order's date and its total and its id, we need three subqueries, and if we want the three latest orders, a scalar subquery cannot express it at all, because it would return three rows.
A normal subquery in FROM, a derived table, can return many rows and columns, but it cannot refer to other tables in the same FROM clause. It is computed independently, as if the other tables did not exist. LATERAL removes exactly that restriction.
2What LATERAL Adds
The LATERAL keyword in front of a subquery in FROM allows it to refer to columns of tables listed before it. For each row of the left side, the subquery is evaluated with that row's values, and its rows are joined to it. It is a correlated subquery that can return a full result set. SQL Server spells the same idea CROSS APPLY, and OUTER APPLY for the version that keeps outer rows without matches.
CROSS JOIN LATERAL drops customers whose subquery returns nothing, just like an inner join. To keep them, with NULL order columns, we write LEFT JOIN LATERAL (...) o ON true. The ON true is needed because LEFT JOIN syntax requires a condition, and the real condition is already inside the subquery.
3Why It Is Fast With the Right Index
The plan for the LATERAL query is a nested loop: for each customer, run the subquery. With an index on (customer_id, created_at DESC), the subquery becomes an index scan that starts at the newest entry for that customer and stops after three rows because of LIMIT. Each probe reads three index entries and three table rows, whatever the size of the group.
8 messages in order. Play them, or step through them one at a time.
Each probe reads at most N entries, so the cost does not depend on the size of the group.
Let us put numbers on it. With 100,000 customers and an average of 500 orders each, the orders table has 50 million rows. The LATERAL plan reads about 100,000 x 3 = 300,000 index entries and rows. The table could double in size and the work would stay the same, because it depends on the number of customers and N, not on the size of the groups. If we only want the top 3 for one page of 20 customers, it reads 60 rows.
4The ROW_NUMBER Alternative
The other standard approach numbers the rows within each group with a window function and keeps the first N.
| LATERAL + LIMIT | ROW_NUMBER() window | |
|---|---|---|
| Reads | Outer rows x N | Every row of the table |
| Needs | Index on (group key, order key) | A sort or an ordered index scan |
| Best when | Large groups, or a subset of groups | Small groups, every group needed |
| 100k customers x 500 orders, N = 3 | About 300,000 rows | 50,000,000 rows |
| 10M customers x 2 orders, N = 3 | 10,000,000 probes | One pass over 20,000,000 rows |
This is portable and easy to read, but notice what it does: it must read every order, all 50 million rows, assign a number to each, and then throw away all but 300,000. It needs the rows sorted by customer and date, either by sorting all of them, which may spill to disk, or by reading the whole composite index in order. Its cost grows with the table, not with the number of results.
But there is a catch for LATERAL too. Its cost is one probe per outer row, and each probe has a fixed overhead. If we have 10 million customers with 2 orders each and want the top 3, LATERAL does 10 million probes to return nearly every row, while ROW_NUMBER does one sequential pass and a sort, which is usually cheaper. So the rule is about group size and selectivity: LATERAL wins when groups are large compared to N, or when we only need some groups; ROW_NUMBER wins when groups are small and we need all of them.
5Support Across Databases
PostgreSQL has supported LATERAL since 9.3. SQL Server has CROSS APPLY and OUTER APPLY. MySQL added LATERAL derived tables in 8.0.14, with the same meaning, so the query above works there with the same index advice; check your version and its plan, since MySQL's optimizer handles the LIMIT inside differently from PostgreSQL in some versions. Oracle supports both LATERAL and CROSS APPLY in recent releases. LATERAL is also useful beyond top-N: calling a set-returning function per row, such as unnest of an array column, or computing several derived values once and reusing them in the select list.
6Follow-up questions
Is DISTINCT ON a good alternative for top-1 in PostgreSQL?
For top 1 per group, SELECT DISTINCT ON (customer_id) * FROM orders ORDER BY customer_id, created_at DESC is concise and reads the table once in order, so it behaves like the ROW_NUMBER approach: good when we need every group and groups are small. It cannot do top 3. For a few groups out of many, or large groups, LATERAL with LIMIT 1 is still faster.
Does the planner ever turn a ROW_NUMBER query into LATERAL probes on its own?
Generally no. PostgreSQL can push the rn <= 3 condition into the window computation to stop early within each partition in recent versions, which saves some work, but it still reads every partition. The probe-per-group strategy is something we have to ask for by writing LATERAL. That is why knowing both forms matters.
How would you write this in JPA?
JPQL has no LATERAL, so we use a native query with an interface or record projection. Hibernate 6 does support some lateral joins in HQL (check your version), but a native query is clearer and lets us control the plan. For simple top-1 needs, a select-list subquery with MAX plus the right index may be enough and stays in JPQL.
7Conclusion
In this answer, we saw that a correlated subquery in the select list can return only one value, while LATERAL or CROSS APPLY lets a subquery in FROM use the outer row and return many rows and columns. For top-N per group, LATERAL with ORDER BY and LIMIT over an index on (customer_id, created_at DESC) reads only N entries per group, which wins when groups are large or only some are needed, while ROW_NUMBER reads every row and wins when groups are small and all are needed. MySQL supports LATERAL from 8.0.14.
Open with
A correlated subquery in the select list has to be scalar, one row and one column per outer row, so it can give me the latest order date but not the latest order's whole row, and not the three latest orders.
Then, if they want more
LATERAL, or CROSS APPLY in SQL Server, is a subquery in FROM that can refer to the tables before it, so it runs per outer row and can return several rows and columns.
For top three orders per customer I would write FROM customers c CROSS JOIN LATERAL, a subquery selecting from orders where customer_id = c.id, ordered by created_at descending, limit 3. If I need customers without orders too, LEFT JOIN LATERAL ...
ON true. The reason it is fast is the index on customer_id, created_at descending: each probe starts at the newest entry for that customer and stops after three. So with 100,000 customers and 500 orders each, I read about 300,000 rows instead of 50 million, and the work does not grow when groups grow.
The alternative is ROW_NUMBER over a partition by customer, ordered by date, then filter rn <= 3. That reads and numbers every row, so it is worse for large groups, but if groups are tiny, say two orders per customer for 10 million customers, one pass with a sort beats 10 million probes. MySQL supports LATERAL since 8.0.14, and I would check the plan there.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- Hibernate 6
- 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 "What does LATERAL (PostgreSQL) or CROSS APPLY (SQL Server) add over a correlated...": https://scrivio-interview-library.netlify.app/databases/sql-joins-and-subqueries/22420896a2/