Interview's MateSQL Learning
Interview's Mate

SQL Learning

Foundations → production SQL

Visualizer

DSA Visualizer
All 32 lessons
Custom Playground
Try your own examples

Learning

System Design
31 architecture topics
SQL Learning
160 foundations → production topics
AI Engineering
160 LLM → backend topics
Data Science
160 Python → MLOps topics
Data Engineer
160 SQL → streaming topics
Docker
160 Docker learning topics
Kubernetes
160 K8s fundamentals → cloud
Java LearnSoon
Coming soon
Python Learn
Interview Q&A & internals
JavaScript Learn
Closures, async & DOM Q&A
Tech Learn
Search, practise & track Q&A
AI DSA Practice
Solve coding problems
Theme
Home
SQL topics
Lesson 56/ 160
03. Joins & Relational Querying

Top-N Per Group Using LATERAL Joins

Fetch the top N rows per parent efficiently with LATERAL + ORDER BY LIMIT.

AdvancedTop-N · LATERAL LIMIT3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

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

Loading interactive 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.

Top 3 products per category by revenue, precomputedQuery example
1Input dataStart from the source rows or state that the statement sees.
This statement works with the current schema, configuration, or database state rather than a row dataset. The command still follows the same input → query → result flow.
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.name,3  p.name,4  p.revenue5FROM6  categories c7  CROSS JOIN LATERAL (8    SELECT9      name,10      revenue11    FROM12      product_revenue13    WHERE14      category_id = c.id15    ORDER BY16      revenue DESC17    LIMIT18      319  ) p;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/19
3OutputInspect the representative rows, affected-row count, plan, or command status.
Top revenue products by category3 sample rows
Top revenue products by category
categoryproductrevenue
ElectronicsNoise-canceling headphones980000
ElectronicsSmart watch755000
HomeEspresso machine420000

Note: Illustrative product_revenue data; the composite index improves the per-category ordered lookup but does not determine values.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

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.

Keep customers with no ordersQuery example
1Input dataStart from the source rows or state that the statement sees.
customers
3 rows
customers sample rows
idnameemailcity
1Mayamaya@example.comPune
2Raviravi@example.comDelhi
3Noornoor@example.comMumbai
orders
3 rows
orders sample rows
idcustomer_idstatusamountcoupon_code
1011paid249NULL
1022paid120WELCOME10
1031shipped89.5NULL
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  c.id,3  o.id AS order_id,4  o.created_at5FROM6  customers c7  LEFT JOIN LATERAL (8    SELECT9      id,10      created_at11    FROM12      orders13    WHERE14      customer_id = c.id15    ORDER BY16      created_at DESC,17      id DESC18    LIMIT19      220  ) o ON TRUE;
Logical execution order
Native / baseline

PostgreSQL is the lesson baseline unless noted otherwise.

Line 1 · Project and calculate

Calculate the selected expressions and return the requested output columns.

1/20
3OutputInspect the representative rows, affected-row count, plan, or command status.
Newest orders with null-preserving join3 sample rows
Newest orders with null-preserving join
idorder_idcreated_at
75012026-11-21 09:10:00
74992026-11-18 15:30:00
8NULLNULL

Note: Assumes customer 7 has two or more orders and customer 8 has none; the LEFT join preserves the latter as NULL order fields.

4ExplanationConnect the result back to the SQL rule and the edge case it demonstrates.

Key takeaway: LEFT JOIN LATERAL … ON true keeps empty groups; add a tie-breaker.

Interactive walkthrough

How it works, step by step

Follow one practical SQL workflow from start to finish. Select any step or play through the flow.

Progress1/4
Step 1Outer query

Identify the driving table

Pick the table with one row per group (devices, customers, categories). That's the loop the LATERAL subquery runs for.

SQL at this step
1FROM2  devices d
What to watch at this step
Loops
one per row
Tip: use ← → to move between steps

When 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

LATERAL + ORDER BY + LIMIT
Best for: Few rows per group from a large, indexed child table

Strengths: Reads only what it returns; scales with groups × N.

Watch out: Slow without a matching index; needs a driving table.

ROW_NUMBER() + filter
Best for: Portable SQL, or when most rows are needed anyway

Strengths: Works everywhere; one pass; flexible ranking.

Watch out: Ranks every row before filtering.

DISTINCT ON (PostgreSQL)
Best for: Top 1 per group only

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?
Interview tip: Give both solutions, then explain the cost difference: ROW_NUMBER ranks the whole table, LATERAL reads groups × N rows with the right index. Naming the index seals it.

Knowledge check

Loading quiz

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.

Open SQL Practice →SQL interview Q&A
Previous topic
LATERAL Joins (Correlated Subqueries in the FROM Clause)
Next topic
Combining Joins with Aggregations Safely