Quick revision
The short answer
Use a LATERAL join: SELECT o.* FROM unnest(:ids) AS c(id) CROSS JOIN LATERAL (SELECT * FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 5) o. Each probe is an index range scan on (customer_id, created_at DESC) that stops after 5 entries, so the query costs about 10,000 small index lookups. The ROW_NUMBER version must read and rank every order of those customers, or of the whole table, before it can keep 5 per customer.
What to remember
In this answer, we replaced the ROW_NUMBER() OVER (PARTITION BY customer_id ...) query with a LATERAL join over unnest(:ids), whose inner query orders one customer's orders by created_at DESC and takes LIMIT 5. Each probe is an index range scan on (customer_id, created_at DESC) that stops after 5 entries, so the cost is about 10,000 small index lookups, while the window version must read every order of the selected customers, or the whole table, before it can rank. MySQL supports LATERAL from 8.0.14, with a correlated subquery or UNION ALL as fallbacks, and batching the ids and a covering index with INCLUDE make the query cheaper still.
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.
Use a LATERAL join: SELECT o.* FROM unnest(:ids) AS c(id) CROSS JOIN LATERAL (SELECT * FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 5) o. Each probe is an index range scan on (customer_id, created_at DESC) that stops after 5 entries, so the query costs about 10,000 small index lookups. The ROW_NUMBER version must read and rank every order of those customers, or of the whole table, before it can keep 5 per customer.
Why this question is asked
This is the kind of query that works fine in development and takes minutes in production. The window function version is the textbook answer to "top N per group", and it is correct, but on 500 million rows it does far more work than the question needs. Interviewers ask it as an internals question because the fix is not a trick: it follows from understanding how a B-tree index is laid out and how the executor runs each plan. In this answer, we will recap the index, look at what the window plan really does, write the LATERAL version, read its plan, handle MySQL, and tune the last details.
1A Quick Recap of the Index
A B-tree index on (customer_id, created_at DESC) stores one entry per order, sorted first by customer and then, within each customer, from the newest order to the oldest. So all of customer 42's orders sit next to each other, newest first. Finding them is a descent from the root of the tree to the first entry for customer 42, which costs a handful of page reads, about 4 or 5 levels for 500 million entries, and then reading entries one after another.
That layout already contains our answer. The 5 latest orders of a customer are simply the first 5 entries of that customer's section of the index. A good plan should jump there, read 5 entries and stop.
2What the ROW_NUMBER Version Really Does
Here is the slow query.
To number rows within each customer, the window function must see all of each customer's orders, in order, before the outer filter can discard the rest. If the 10,000 customers have 300 orders each on average, that is 3 million rows read, often from the table itself because SELECT * needs every column, and possibly sorted. If the planner decides that 10,000 ids are too many for index lookups, it may scan all 500 million rows instead and sort them by customer. Either way, the work grows with the total number of orders of these customers, while the result only needs 5 per customer. PostgreSQL 15 and later can stop a window early with a run condition in some cases, but with PARTITION BY it still has to process every partition, so it does not fix this.
3The LATERAL Version
LATERAL lets a subquery in FROM refer to columns of the items listed before it. We turn the id list into rows with unnest, and for each id we run a tiny query: the 5 newest orders of that customer. That is exactly the shape the index serves.
| Plan | Rows read | Sort | Grows with |
|---|---|---|---|
ROW_NUMBER, index lookups | all their orders, about 3 million | maybe, per customer | orders per customer |
ROW_NUMBER, seq scan | 500 million | yes, whole table | table size |
| LATERAL with LIMIT 5 | 50,000 | none, index order | number of customers |
Notice that nothing about the result changed: 5 latest orders per customer, customers with fewer orders return fewer rows, and customers with none return nothing (LEFT JOIN LATERAL ... ON true would keep them). What changed is the amount of work. Each inner query is a descent into the index plus 5 entries, so the total is about 10,000 x (5 levels + 5 entries + 5 table rows), a few hundred thousand page accesses at most, many of them already in cache. From Spring, :ids can be bound as a Java long array through JDBC's createArrayOf, so the whole list is one parameter.
4Reading the LATERAL Plan
EXPLAIN ANALYZE confirms the shape. We want a nested loop driven by the unnest function, with a Limit over an index scan inside it, executed once per customer, and no Sort node.
8 messages in order. Play them, or step through them one at a time.
Each probe costs a few page reads, no matter how many orders the customer has.
Notice loops=10000 with rows=5 per loop: each probe reads exactly what it returns. If instead we see a Sort under the Limit, the index order does not match the ORDER BY, for example because the index is on (customer_id, created_at) ascending while a different ORDER BY is used, or a NULLS clause differs, and the database must fetch and sort all of each customer's orders again. A backward scan of an ascending index also works for ORDER BY created_at DESC, so the important thing is that the column order and directions match.
5MySQL and Other Fallbacks
MySQL supports LATERAL derived tables since 8.0.14, so the same idea works there. MySQL has no unnest, so the id list comes from a temporary table, a VALUES list or JSON_TABLE over a JSON array. On older versions, or in databases without LATERAL, the fallbacks are a correlated subquery that fetches each customer's 5 newest order ids, or a generated UNION ALL of per-customer queries, each with its own ORDER BY and LIMIT, batched in groups.
6Tuning the Last Details
Two small changes make it even better. First, batch the 10,000 ids into a few requests, say four of 2,500, which keeps each statement short, spreads the load and lets the API stream results. Second, consider a covering index. If the API needs only id, created_at and total, PostgreSQL's INCLUDE clause can store those extra columns in the index leaf entries, so the probe becomes an index-only scan that never visits the table.
Index-only scans need the visibility map to be up to date, which vacuum maintains; on a table with heavy updates, some heap fetches remain. And the covering index is a second index to maintain on every insert, so we add it only if the endpoint is hot enough to justify the extra write cost.
7Follow-up questions
What would you do if one customer has 2 million orders and most have 3?
Nothing special for this query: the LATERAL probe for the big customer still reads only 5 index entries and stops, which is exactly why it is robust to skew. The window version is the one that suffers, because it would read and rank all 2 million orders. Skew matters only for queries that need all of a customer's rows, where we would page with keyset pagination instead.
When is the window version the better choice?
When we need most rows of each group, or all groups of a whole table, for example a nightly job ranking every customer's orders. Then reading everything is unavoidable, and one sequential pass with a window can be cheaper than millions of index probes.
Why bind the ids as an array instead of a long IN list?
One array parameter keeps the statement text the same for any number of ids, so the prepared statement and its plan can be reused, and it avoids parameter limits and huge SQL strings.
8Conclusion
In this answer, we replaced the ROW_NUMBER() OVER (PARTITION BY customer_id ...) query with a LATERAL join over unnest(:ids), whose inner query orders one customer's orders by created_at DESC and takes LIMIT 5. Each probe is an index range scan on (customer_id, created_at DESC) that stops after 5 entries, so the cost is about 10,000 small index lookups, while the window version must read every order of the selected customers, or the whole table, before it can rank. MySQL supports LATERAL from 8.0.14, with a correlated subquery or UNION ALL as fallbacks, and batching the ids and a covering index with INCLUDE make the query cheaper still.
Open with
The window version has to read every order of the selected customers, or with a bad estimate the whole 500 million row table, and rank them all before the outer filter keeps five per customer.
Then, if they want more
So its cost grows with the number of orders, not with the size of the answer. The index on customer and created at descending already holds the answer: each customer's orders are adjacent, newest first, so the five latest are the first five entries of that section.
I would write it as select from unnest of the id array as c, cross join lateral a subquery that selects from orders where customer id equals c dot id, order by created at descending, limit five.
The plan becomes a nested loop with 10,000 loops, each one an index scan that descends a few levels, reads five entries and stops, so the total is about 10,000 small lookups, typically well under a second. I would confirm in EXPLAIN ANALYZE that there is no sort under the limit, which means the index order matches the order by.
MySQL supports lateral from 8.0.14, using JSON_TABLE or a temporary table for the id list, with a correlated subquery or union all as a fallback. Then I would batch the ids into a few requests and, if the endpoint is hot, add a covering index with INCLUDE so the probes become index-only scans.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- MySQL 8.0, PostgreSQL 15
- 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 "orders(id, customer_id, created_at, total) has 500 million rows and an index on...": https://scrivio-interview-library.netlify.app/databases/sql-coding-problems/6429e32410/