Top-N Per Group Using LATERAL Joins
Fetch the top N rows per parent efficiently with LATERAL + ORDER BY LIMIT.
In plain words
For each group, go and fetch just its top few rows, rather than sorting everything first.
Think of it like…
Asking each shop manager to bring their top 3 sellers, instead of piling every sales receipt from every shop on one table and sorting the whole heap.
Where you’ve seen it
An IoT dashboard shows the latest 5 readings for each of 12,000 devices from a 2-billion-row readings table: SELECT d.id, r.reading_at, r.value FROM devices d CROSS JOIN LATERAL (SELECT reading_at, value FROM readings WHERE device_id = d.id ORDER BY reading_at DESC LIMIT 5) r; With an index on readings (device_id, reading_at DESC) it runs in milliseconds; the ROW_NUMBER version scans the whole table.
Words you’ll hear
- LATERAL
- Lets a subquery in FROM reference columns of tables listed before it.
- CROSS JOIN LATERAL
- Drops parents whose subquery returns no rows.
- LEFT JOIN LATERAL … ON true
- Keeps parents with no children, with NULL columns.
- CROSS APPLY / OUTER APPLY
- SQL Server's equivalents of CROSS and LEFT JOIN LATERAL.
Visual diagram
Theory & example queries
Why LATERAL can be so much faster
ROW_NUMBER() OVER (PARTITION BY device_id ORDER BY reading_at DESC) has to compute a rank for every reading in the table, and only then can the outer query keep rn <= 5. The cost grows with the size of the child table. A LATERAL subquery with LIMIT 5 and a matching index jumps straight to each device's newest entry and stops after five, so the cost grows with the number of groups times N.
The index must match both the filter and the sort: CREATE INDEX ON readings (device_id, reading_at DESC). Without it, each lateral subquery scans and sorts, and doing that thousands of times is far worse than one window-function pass. So the rule of thumb: a big child table, a small N and a matching index favour LATERAL; no index, or needing most rows anyway, favours ROW_NUMBER.
SELECT c.name, p.name, p.revenueFROM categories c CROSS JOIN LATERAL ( SELECT name, revenue FROM product_revenue WHERE category_id = c.id ORDER BY revenue DESC LIMIT 3 ) p;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Top revenue products by category3 sample rows
| category | product | revenue |
|---|---|---|
| Electronics | Noise-canceling headphones | 980000 |
| Electronics | Smart watch | 755000 |
| Home | Espresso machine | 420000 |
Note: Illustrative product_revenue data; the composite index improves the per-category ordered lookup but does not determine values.
with an index on product_revenue (category_id, revenue DESC).
Key takeaway: LATERAL + LIMIT + matching index costs groups × N, not table size.
Details: empty groups, ties and other databases
CROSS JOIN LATERAL behaves like an inner join, so devices with no readings vanish. Use LEFT JOIN LATERAL (…) r ON true to keep them with NULLs. For ties at the cut-off, FETCH FIRST 5 ROWS WITH TIES (PostgreSQL 13+) includes every row tied with the fifth; otherwise add a unique tie-breaker such as id to ORDER BY so results are deterministic.
If there's no parent table to drive the loop, select the distinct group ids first; on very large tables a recursive CTE that jumps from one group id to the next (a "loose index scan") avoids reading every row. LATERAL is supported in PostgreSQL 9.3+ and MySQL 8.0.14+; SQL Server and Oracle 12c+ use CROSS APPLY and OUTER APPLY.
| id | name | city | |
|---|---|---|---|
| 1 | Maya | maya@example.com | Pune |
| 2 | Ravi | ravi@example.com | Delhi |
| 3 | Noor | noor@example.com | Mumbai |
| id | customer_id | status | amount | coupon_code |
|---|---|---|---|---|
| 101 | 1 | paid | 249 | NULL |
| 102 | 2 | paid | 120 | WELCOME10 |
| 103 | 1 | shipped | 89.5 | NULL |
SELECT c.id, o.id AS order_id, o.created_atFROM customers c LEFT JOIN LATERAL ( SELECT id, created_at FROM orders WHERE customer_id = c.id ORDER BY created_at DESC, id DESC LIMIT 2 ) o ON TRUE;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Newest orders with null-preserving join3 sample rows
| id | order_id | created_at |
|---|---|---|
| 7 | 501 | 2026-11-21 09:10:00 |
| 7 | 499 | 2026-11-18 15:30:00 |
| 8 | NULL | NULL |
Note: Assumes customer 7 has two or more orders and customer 8 has none; the LEFT join preserves the latter as NULL order fields.
Key takeaway: LEFT JOIN LATERAL … ON true keeps empty groups; add a tie-breaker.
How it works, step by step
Follow one practical SQL workflow from start to finish. Select any step or play through the flow.
Identify the driving table
Pick the table with one row per group (devices, customers, categories). That's the loop the LATERAL subquery runs for.
FROM devices dWhen to use it & trade-offs
What it is
A LATERAL join runs a small subquery once for each row of the outer table, and that subquery can use the outer row's columns. For top-N per group, the subquery is just ORDER BY … LIMIT n filtered to the current group. With an index on (group_id, sort_column), each group costs a few index reads, so finding the 5 latest readings for 1,000 devices touches about 5,000 rows instead of sorting billions.
Why it matters: The usual ROW_NUMBER() solution ranks every row in the table before throwing most of them away. When the child table is huge and you only need a handful of rows per parent, LATERAL with an index is often orders of magnitude faster. Senior SQL interviews ask when you'd pick one over the other, not just how to write each.
When to reach for it
- Latest N events, readings or orders per entity
- Top N products per category for a page
- Dashboards over large time-series tables
When to avoid or be careful
- LATERAL without an index on (group, sort)
- Large N, where most rows are read anyway
- CROSS JOIN LATERAL when groups with no rows must still appear
LATERAL vs ROW_NUMBER vs DISTINCT ON for top-N per group
Strengths: Reads only what it returns; scales with groups × N.
Watch out: Slow without a matching index; needs a driving table.
Strengths: Works everywhere; one pass; flexible ranking.
Watch out: Ranks every row before filtering.
Strengths: Very short to write.
Watch out: Only one row per group; PostgreSQL only.
Interview signals & numbers to know
When this topic comes up
- “Latest 5 orders per customer, the table has a billion rows”
- “The ROW_NUMBER query is too slow”
- Per-group LIMIT
- CROSS APPLY in SQL Server
- Time-series dashboards
Benchmarks & rules of thumb
- groups × N
- rows read by an indexed LATERAL query
- PostgreSQL 9.3
- LATERAL support
- MySQL 8.0.14
- LATERAL support
- PostgreSQL 13
- FETCH FIRST … WITH TIES
Common mistakes & follow-ups
Common interview mistakes
- Writing the LATERAL query without the (device_id, reading_at DESC) index and finding it slower than ROW_NUMBER.
- Using CROSS JOIN LATERAL and losing customers who have no orders.
- Sorting only by created_at, so ties make the top N change between runs.
Likely interviewer follow-ups
- When is LATERAL faster than ROW_NUMBER for top-N per group, and when isn't it?
- Which index would make this LATERAL query fast?
- How do you write the same query in SQL Server?
Knowledge check
Put it into practice
Practice related interview Q&A
Apply Top-N Per Group Using LATERAL Joins with hands-on SQL practice and interview Q&A.