Quick revision
The short answer
SELECT c.id, o.* FROM customers c CROSS JOIN LATERAL (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 3) o returns each customer with their three latest orders. LATERAL lets the subquery refer to c, so it runs once per customer and its LIMIT applies per customer, whereas a plain join's LIMIT applies to the whole result and a normal derived table cannot see c at all. LEFT JOIN LATERAL (...) ON true keeps customers with no orders, and an index on orders(customer_id, created_at DESC) makes each probe a short index scan.
What to remember
In this answer, we returned each customer's three most recent orders with CROSS JOIN LATERAL. A plain join's LIMIT applies to the whole result, and an ordinary derived table cannot refer to the customer, while a LATERAL subquery can refer to earlier FROM items and so runs once per customer with its own ORDER BY and LIMIT. LEFT JOIN LATERAL ... ON true keeps customers without orders, an index on orders(customer_id, created_at DESC) makes each probe a short index scan, MySQL supports LATERAL since 8.0.14, and SQL Server calls it CROSS APPLY.
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.
SELECT c.id, o.* FROM customers c CROSS JOIN LATERAL (SELECT * FROM orders o WHERE o.customer_id = c.id ORDER BY created_at DESC LIMIT 3) o returns each customer with their three latest orders. LATERAL lets the subquery refer to c, so it runs once per customer and its LIMIT applies per customer, whereas a plain join's LIMIT applies to the whole result and a normal derived table cannot see c at all. LEFT JOIN LATERAL (...) ON true keeps customers with no orders, and an index on orders(customer_id, created_at DESC) makes each probe a short index scan.
Why this question is asked
'Latest N per group' is one of the most common requirements in any application: the three most recent orders on a customer page, the last five messages per conversation, the top two reviews per product. Developers often try to solve it with a join and a LIMIT and get the wrong answer, then fall back to N+1 queries from Java. Interviewers ask for the LATERAL version because it shows we understand how SQL scopes subqueries and how to make a per-row query fast. In this answer, we will see why the plain join cannot work, recap what LATERAL changes, write the query, keep customers without orders, make it fast with the right index, and look at other engines.
1Why a Plain Join With LIMIT Cannot Do This
The first attempt usually looks like this.
LIMIT applies to the final result of the query, not to each customer. So we get three rows overall. The second attempt is to put the LIMIT inside a subquery in the FROM clause, a derived table.
2Why a Normal Derived Table Cannot See the Customer
We would like to write the subquery 'the three latest orders of this customer'. But a subquery in FROM is evaluated as an independent table, and it cannot refer to columns of other tables in the same FROM clause.
The error is the rule we need to break. Without a reference to c, the subquery could only compute the three latest orders overall, again the wrong answer.
3A Quick Recap of LATERAL
The LATERAL keyword changes exactly that rule. A LATERAL subquery may refer to columns of FROM items that appear before it. Logically, the database then evaluates the subquery once for each row of those earlier items, with that row's values plugged in, and joins the results. It works like a for-each loop written in SQL: for each customer, run this query.
4Writing the Query
With LATERAL, the subquery can filter by c.id, and its ORDER BY and LIMIT now apply per customer.
8 messages in order. Play them, or step through them one at a time.
Customer 1 gets exactly three orders, customer 2 gets the two it has, and customer 3 does not appear. CROSS JOIN LATERAL behaves like an inner join: when the subquery returns no rows for a customer, that customer produces no output rows. If two orders can share a created_at, we add o.id DESC to the ORDER BY so the choice of the third order is deterministic.
5Keeping Customers Without Orders
To list every customer, including those with no orders, we use LEFT JOIN LATERAL. A LEFT JOIN needs an ON condition, but the real condition is already inside the subquery, so we write ON true.
6Making Each Probe Fast
Because the subquery runs once per customer, its cost is multiplied by the number of customers. With an index on orders (customer_id, created_at DESC), each run is a short index scan: jump to the customer's entries, which are stored newest first, read three, and stop. The plan shows a Nested Loop with a Limit over an Index Scan.
For a page that shows 50 customers this is about 50 tiny index scans, a few hundred page reads, regardless of whether the orders table holds a million or a billion rows. The alternative with ROW_NUMBER() OVER (PARTITION BY customer_id ORDER BY created_at DESC) and a filter rn <= 3 computes a rank for every order of every customer it reads, which is far more work when we need only a few customers. When we need the top three for nearly all customers, the balance can tip the other way, which is a good follow-up topic.
It also replaces the N+1 pattern in Java, where the application loads 50 customers and then runs 50 separate queries for their orders. LATERAL does the same per-customer lookup inside one round trip.
7Follow-up questions
Does MySQL support LATERAL?
Yes, since MySQL 8.0.14, with the same JOIN LATERAL syntax for derived tables. SQL Server and Oracle express the same idea with CROSS APPLY and OUTER APPLY, which correspond to CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true.
Can I use LATERAL with a function instead of a subquery?
Yes. In PostgreSQL, set-returning functions in FROM can refer to earlier columns, and LATERAL is implied for them, as in SELECT u.id, t FROM users u, unnest(u.tags) AS t. The keyword is required only for subqueries.
How would you return the three orders as an array or JSON per customer instead of rows?
Aggregate inside the lateral subquery: LEFT JOIN LATERAL (SELECT json_agg(x) AS recent FROM (SELECT o.id, o.created_at FROM orders o WHERE o.customer_id = c.id ORDER BY o.created_at DESC LIMIT 3) x) r ON true. Each customer then produces exactly one row, which is convenient for an API response.
8Conclusion
In this answer, we returned each customer's three most recent orders with CROSS JOIN LATERAL. A plain join's LIMIT applies to the whole result, and an ordinary derived table cannot refer to the customer, while a LATERAL subquery can refer to earlier FROM items and so runs once per customer with its own ORDER BY and LIMIT. LEFT JOIN LATERAL ... ON true keeps customers without orders, an index on orders(customer_id, created_at DESC) makes each probe a short index scan, MySQL supports LATERAL since 8.0.14, and SQL Server calls it CROSS APPLY.
Open with
I'd write SELECT c.id and the order columns FROM customers c CROSS JOIN LATERAL a subquery: SELECT from orders o WHERE o.customer_id equals c.id ORDER BY created_at DESC LIMIT 3.
Then, if they want more
The LATERAL keyword is what makes this possible. A normal subquery in FROM is evaluated as an independent table and can't reference c, PostgreSQL even raises an error for it, while a LATERAL subquery can refer to columns of earlier FROM items, so logically it runs once per customer and its LIMIT applies per customer.
A plain join with LIMIT 3 at the end doesn't work because the LIMIT applies to the whole result, so you get three rows overall. If I want customers without orders too, I use LEFT JOIN LATERAL with ON true, and they come back with NULLs.
For performance I'd make sure there's an index on orders customer_id and created_at descending, so each lateral probe is a short index scan that reads three entries and stops; for a page of customers that's very cheap compared with ranking every order with ROW_NUMBER. I'd add the order id as a tiebreaker if timestamps can repeat.
MySQL supports LATERAL since 8.0.14, and in SQL Server the equivalent is CROSS APPLY.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.0
- 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 "Return each customer with their three most recent orders using a LATERAL join in...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/0b892c63e0/