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 55/ 160
03. Joins & Relational Querying

LATERAL Joins (Correlated Subqueries in the FROM Clause)

Reference left-side columns inside FROM subqueries with LATERAL.

AdvancedLATERAL · Correlated · Top-N3 quiz questions
Practice SQL
In plain wordsDiagramExamples & theoryStep by stepWhen to use itInterview cluesMistakes to avoidQuiz (3)Practice

In plain words

LATERAL lets a subquery use the current row's values, so you can say "for each of these, get me those".

Think of it like…

For each customer card in a stack, you pull their file and photocopy only their three most recent invoices. The pull depends on which card you're holding.

Where you’ve seen it

A customer list showing each customer's three most recent orders: SELECT c.name, o.id, o.created_at FROM customers c CROSS JOIN LATERAL (SELECT id, created_at FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 3) o; With an index on orders(customer_id, created_at DESC), each lookup reads just three index entries.

Words you’ll hear

LATERAL
Lets a FROM-clause subquery reference earlier FROM items.
CROSS JOIN LATERAL
Keeps only left rows for which the subquery returns rows (like CROSS APPLY).
LEFT JOIN LATERAL … ON true
Keeps every left row, with NULLs when the subquery returns nothing (like OUTER APPLY).
Per-row execution
The subquery is evaluated for each left row, so an index matters.

Visual diagram

Loading interactive diagram

Theory & example queries

What LATERAL allows

Normally each item in FROM is independent: a derived table can't mention columns from another table in the same FROM. LATERAL removes that restriction for the subquery it marks, which can then use columns from any FROM item to its left, typically in its WHERE.

Because it can return many rows and many columns per outer row, it handles what correlated scalar subqueries can't: "top N related rows", "several values computed together", or calling a set-returning function with arguments from the row (PostgreSQL treats function calls in FROM as implicitly lateral).

Keeping customers who have 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.name,3  o.id4FROM5  customers c6  LEFT JOIN LATERAL (7    SELECT8      id9    FROM10      orders11    WHERE12      customer_id = c.id13    ORDER BY14      created_at DESC15    LIMIT16      317  ) 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/17
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative latest orders per customer4 sample rows
Representative latest orders per customer
nameid
Asha Rao503
Asha Rao501
Kabir Shah498
Mina DasNULL

Note: Illustrative rows show at most three latest order ids per customer; Mina remains present with NULL because LEFT JOIN LATERAL is used.

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

Key takeaway: LATERAL = a FROM subquery that can see the current outer row.

Performance: when it shines and when it hurts

LATERAL runs the subquery per outer row, so it's fast when that subquery is an index seek that touches a handful of rows, such as top-N per group with an index on (group, sort column). For a few thousand customers it can beat a window-function solution that sorts every order.

Without a supporting index, every outer row scans the inner table, and the cost multiplies. If the outer side has millions of rows and you need all related rows anyway, a plain join or a window function over the whole table is usually better. Check EXPLAIN for a Nested Loop whose inner side is an Index Scan.

Two values computed together per rowQuery example
1Input dataStart from the source rows or state that the statement sees.
order_items
3 rows
order_items sample rows
idorder_idproduct_idqtyprice
110142249.5
2101841150
310242149.5
products
3 rows
products sample rows
idnamepricecategorystock
42SQL Notebook49.5books18
84Mechanical Keyboard150hardware5
11Query Mug12.99gifts33
2QuerySwitch dialects, then select a line or execution step to trace it.
query.sql
1SELECT2  p.name,3  s.total,4  s.orders5FROM6  products p7  CROSS JOIN LATERAL (8    SELECT9      SUM(qty) AS total,10      COUNT(*) AS orders11    FROM12      order_items13    WHERE14      product_id = p.id15  ) s;
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/15
3OutputInspect the representative rows, affected-row count, plan, or command status.
Representative product activity3 sample rows
Representative product activity
nametotalorders
Mechanical Keyboard4832
SQL Handbook11287
USB-C HubNULL0

Note: Illustrative aggregates per product. The aggregate subquery always returns one row, so products with no items remain in this CROSS JOIN LATERAL form with total NULL and count zero.

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

Key takeaway: Great with an index and a small outer side; check the plan otherwise.

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 1Problem

Identify the "for each"

Name the outer rows (each customer) and what you need per row (their latest three orders).

Focus at this step

for each customer → 3 latest orders

What to watch at this step
Outer
customers
Tip: use ← → to move between steps

When to use it & trade-offs

What it is

A LATERAL subquery in FROM can refer to columns of tables listed before it, so it runs once per row of the left side, like a correlated subquery that returns whole rows. PostgreSQL, MySQL 8.0.14+ and Oracle use LATERAL; SQL Server and Oracle use CROSS APPLY / OUTER APPLY.

Why it matters: Some questions need "for each row, fetch these related rows": the 3 latest orders per customer, or the nearest store per user. A normal subquery in FROM can't see the outer row, and a correlated subquery in SELECT can return only one value. LATERAL fills that gap, and with the right index it's often the fastest way to do top-N per group.

When to reach for it

  • Top-N related rows per parent
  • Several aggregates per row computed together
  • Calling functions with arguments from each row

When to avoid or be careful

  • LATERAL over millions of outer rows without an index
  • CROSS JOIN LATERAL when parents without children must be kept
  • Using it where a plain join already answers the question

LATERAL vs window function vs correlated scalar subquery

LATERAL join
Best for: Top-N or several columns per outer row, with an index

Strengths: Reads only the rows needed per group.

Watch out: Slow without a supporting index; dialect differences.

Window function + filter
Best for: Top-N per group when you'd scan most rows anyway

Strengths: Portable and set-based.

Watch out: Ranks every row before filtering.

Correlated scalar subquery
Best for: Exactly one value per row

Strengths: Simple.

Watch out: Can't return several rows or columns.

Interview signals & numbers to know

When this topic comes up

  • “For each customer, get their 3 latest orders”
  • CROSS APPLY in SQL Server code
  • Top-N per group on a large table
  • “Correlated subquery in FROM”
  • Per-row lookups

Benchmarks & rules of thumb

MySQL 8.0.14 -
first MySQL version with LATERAL
ON true -
join condition for LEFT JOIN LATERAL
N -
index entries read per outer row for LIMIT N

Common mistakes & follow-ups

Common interview mistakes

  • Using CROSS JOIN LATERAL and losing customers who have no orders.
  • Forgetting the index, so each outer row scans the whole inner table.
  • Trying to reference an outer column in a normal (non-LATERAL) derived table and getting an error.

Likely interviewer follow-ups

  • How would you return each customer's latest order, including customers with none?
  • When is LATERAL faster than a window function for top-N per group?
  • What's the SQL Server equivalent of LATERAL?
Interview tip: Present LATERAL as "a correlated subquery that can return rows", show the top-3 orders example with LEFT JOIN … ON true, and mention the index. That covers syntax, semantics and performance.

Knowledge check

Loading quiz

Put it into practice

Practice related interview Q&A

Apply LATERAL Joins (Correlated Subqueries in the FROM Clause) with hands-on SQL practice and interview Q&A.

Open SQL Practice →SQL interview Q&A
Previous topic
Semi-Joins & Anti-Joins (EXISTS, NOT EXISTS, IN, NOT IN Pitfalls with NULL)
Next topic
Top-N Per Group Using LATERAL Joins