Quick revision
The short answer
A LATERAL top-N query becomes a nested loop: one index probe per outer row, costing roughly outer rows times (log n plus N rows), so it wins when the outer set is small or filtered and the inner table is large and well indexed. A ROW_NUMBER query must read and sort, or index-scan, the whole inner table and then filter, so it wins when we need the top N for almost every group and one sequential pass is cheaper than millions of random probes. Without a suitable index, LATERAL degenerates into a repeated scan per outer row and is disastrous.
What to remember
In this answer, we compared the plan shapes of LATERAL and ROW_NUMBER top-N queries. LATERAL is a nested loop with one index probe per outer row, costing about outer rows times (log n plus N), so it wins when the outer set is small or filtered and the inner table is large and well indexed, and it is especially good for groups with very many rows. The window form reads, sorts or index-scans the whole inner table once and filters, so it wins when we need nearly every group. Without a suitable index, LATERAL becomes a scan per outer row and is disastrous, and EXPLAIN (ANALYZE, BUFFERS) confirms the choice.
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 LATERAL top-N query becomes a nested loop: one index probe per outer row, costing roughly outer rows times (log n plus N rows), so it wins when the outer set is small or filtered and the inner table is large and well indexed. A ROW_NUMBER query must read and sort, or index-scan, the whole inner table and then filter, so it wins when we need the top N for almost every group and one sequential pass is cheaper than millions of random probes. Without a suitable index, LATERAL degenerates into a repeated scan per outer row and is disastrous.
Why this question is asked
Both forms of the top-N-per-group query return the same rows, and teams often pick one by habit. The performance difference between them can be a factor of a thousand in either direction, depending on how many groups we need and how the data is laid out. Interviewers ask this internals question to see whether we can reason from plan shapes and data distribution instead of rules of thumb. In this answer, we will look at the plan each form produces, estimate their costs with concrete numbers, see when each one wins, look at what happens without an index, and finish with how to verify the choice.
1The Two Queries We Are Comparing
Both return the three latest orders for a set of customers. The LATERAL form runs a small query per customer; the window form ranks orders and keeps the first three per customer.
We assume orders(customer_id, created_at DESC) is indexed, 100 million orders, and 1 million customers, so about 100 orders per customer on average.
2The Plan Shape of LATERAL
PostgreSQL executes the LATERAL form as a nested loop. The outer side produces customers; for each one, the inner side runs the subquery with c.id filled in, which, with the index, is a Limit over an Index Scan that descends the B-tree to the customer's entries and reads three of them.
The cost is roughly the number of outer rows times the cost of one probe. A probe costs a B-tree descent, about log n, which for 100 million entries is 3 or 4 page reads, plus reading N rows from the heap, usually a few more random page reads. For 2,000 NZ customers that is about 2,000 times 7, around 14,000 page reads, most of them cached: milliseconds. Notice that this cost does not depend on the size of orders except through the logarithm. A customer with 2 million orders costs the same as one with 5, because the probe stops after three.
3The Plan Shape of the Window Query
The window form must compute ROW_NUMBER for every order it reads, because the rank of an order depends on its neighbours in the partition. The filter on country does not reduce the orders that are ranked, unless the planner can push a join condition below the window, which it generally cannot.
So the cost is a full pass over 100 million orders, either a sequential scan plus a large sort, or a full index scan that returns rows in order. That is seconds to minutes. PostgreSQL 15 and later can stop the window early within each partition once rn exceeds 3 (the plan shows a Run Condition), which saves the computation but still visits every partition; check your version's plan for how much it skips.
4When Each One Wins
With the numbers above, LATERAL wins by orders of magnitude for 2,000 customers. Now flip the question: we need the top three for all 1 million customers, for a nightly export. LATERAL now does 1 million probes, each a B-tree descent and a few random heap reads, around 7 million mostly random page reads. The window form reads the table once sequentially, 100 million rows in perhaps 1.5 million sequential pages, and sorts them, or streams them in index order. Sequential reads are much cheaper per page than random reads, and the window avoids repeated B-tree descents, so here the single pass usually wins.
Data distribution shifts the balance too. If most customers have only one or two orders, a probe finds little and the window pass does little extra work per customer, so the window is competitive even for fairly small outer sets. If a few customers have millions of orders, LATERAL is excellent for them, because it reads three rows and stops, while the window must read and rank all of those millions.
| Case | LATERAL | ROW_NUMBER window |
|---|---|---|
| 2,000 customers (filtered) | 2,000 probes, about 14K page reads | Full pass over 100M orders |
| All 1M customers | 1M probes, about 7M random reads | One sequential pass plus sort |
| Few customers with millions of orders | 3 rows per customer, then stop | Reads and ranks every order |
No index on orders(customer_id, ...) | A scan of orders per customer | One pass plus sort, unaffected |
5What Happens Without the Index
The LATERAL form is only fast because each probe can jump straight to one customer's newest orders. Without an index on orders(customer_id, created_at DESC), each probe has to find that customer's orders some other way. With an index on customer_id only, it reads all of the customer's orders and sorts them, which is tolerable. With no index on customer_id at all, each probe is a sequential scan of 100 million orders, and 2,000 probes mean 200 billion row visits. A query that took 10 milliseconds now does not finish.
The window form is not affected in the same way, because it reads the whole table once anyway. That makes LATERAL the higher-reward, higher-risk choice: it depends completely on the index, so we keep the index in the same migration as the query and add a test or a plan check that would catch its removal.
- Is orders indexed on (customer_id, created_at)?YesNext questionNoUse the window, or add the index first
- Do we need few groups compared with all groups?YesLATERAL: one short probe per groupNoNext question
- Are some groups very large?YesLATERAL still helps for thoseNoWindow: one sequential pass
- Confirm with EXPLAIN (ANALYZE, BUFFERS)compare page reads, not only time
4 steps in order. Play them, or step through them one at a time.
6Verifying the Choice
Reasoning gets us to a hypothesis; the plan confirms it. EXPLAIN (ANALYZE, BUFFERS) shows the loops count on the inner side of the nested loop, the rows read by each index scan, and the shared hit and read buffers. Comparing total buffers for both forms on production-sized data, with a cold and a warm cache, is the fairest test. The planner itself also makes this choice when it can: for some forms of the query it can turn one shape into the other, so we should check the plan even when we have written the 'right' query.
7Follow-up questions
Why are random probes so much more expensive than a sequential pass per page?
A sequential scan reads pages in order, which storage and the operating system can prefetch in large chunks, while each index probe reads a few scattered pages that each need their own I/O when not cached. On SSDs the gap is smaller than on spinning disks, but it is still significant, and each probe also pays the CPU cost of a B-tree descent.
Can the window query use the index to avoid the sort?
Yes. An index on (customer_id, created_at DESC) returns orders already grouped by customer and sorted newest first, so the WindowAgg can stream without a Sort node. That makes the window form cheaper, but it still visits every order unless the planner can stop early within partitions.
Is there a hybrid approach for 'all customers' at large scale?
Yes. Keep a small table of the latest three order ids per customer, updated when an order is created, or a materialised view refreshed periodically. Reads then avoid both the probes and the full pass. It is worth it when the query runs often and freshness can be managed.
8Conclusion
In this answer, we compared the plan shapes of LATERAL and ROW_NUMBER top-N queries. LATERAL is a nested loop with one index probe per outer row, costing about outer rows times (log n plus N), so it wins when the outer set is small or filtered and the inner table is large and well indexed, and it is especially good for groups with very many rows. The window form reads, sorts or index-scans the whole inner table once and filters, so it wins when we need nearly every group. Without a suitable index, LATERAL becomes a scan per outer row and is disastrous, and EXPLAIN (ANALYZE, BUFFERS) confirms the choice.
Open with
It comes down to plan shapes. LATERAL runs as a nested loop: for each outer row, one index probe on orders by customer_id and created_at descending, which descends the B-tree and reads N rows and stops.
Then, if they want more
So its cost is roughly the number of outer rows times log n plus N. The ROW_NUMBER version has to compute the rank for every order it reads, so it reads the whole orders table once, either sequentially with a sort or via a full index scan, and then filters rn at most three.
So LATERAL wins when the outer set is small or filtered, say two thousand customers out of a million, and the inner table is large and indexed, because it's a few thousand cheap probes instead of a pass over a hundred million rows. It's also great when some groups are huge, because it stops after three rows.
The window wins when I need the top N for almost every group, like a nightly export of all customers, because one sequential pass is cheaper than a million random probes. And LATERAL depends entirely on the index: without it, each probe becomes a scan of the inner table, and the query is disastrous. I'd verify with EXPLAIN ANALYZE BUFFERS and compare page reads.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- 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 "When is a LATERAL top-N query faster than a ROW_NUMBER window query, and when is it...": https://scrivio-interview-library.netlify.app/databases/advanced-sql/c884932141/