LATERAL Joins (Correlated Subqueries in the FROM Clause)
Reference left-side columns inside FROM subqueries with LATERAL.
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
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).
| 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.name, o.idFROM customers c LEFT JOIN LATERAL ( SELECT id FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 3 ) o ON TRUE;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative latest orders per customer4 sample rows
| name | id |
|---|---|
| Asha Rao | 503 |
| Asha Rao | 501 |
| Kabir Shah | 498 |
| Mina Das | NULL |
Note: Illustrative rows show at most three latest order ids per customer; Mina remains present with NULL because LEFT JOIN LATERAL is used.
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.
| id | order_id | product_id | qty | price |
|---|---|---|---|---|
| 1 | 101 | 42 | 2 | 49.5 |
| 2 | 101 | 84 | 1 | 150 |
| 3 | 102 | 42 | 1 | 49.5 |
| id | name | price | category | stock |
|---|---|---|---|---|
| 42 | SQL Notebook | 49.5 | books | 18 |
| 84 | Mechanical Keyboard | 150 | hardware | 5 |
| 11 | Query Mug | 12.99 | gifts | 33 |
SELECT p.name, s.total, s.ordersFROM products p CROSS JOIN LATERAL ( SELECT SUM(qty) AS total, COUNT(*) AS orders FROM order_items WHERE product_id = p.id ) s;PostgreSQL is the lesson baseline unless noted otherwise.
Calculate the selected expressions and return the requested output columns.
Representative product activity3 sample rows
| name | total | orders |
|---|---|---|
| Mechanical Keyboard | 48 | 32 |
| SQL Handbook | 112 | 87 |
| USB-C Hub | NULL | 0 |
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.
Key takeaway: Great with an index and a small outer side; check the plan otherwise.
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 "for each"
Name the outer rows (each customer) and what you need per row (their latest three orders).
for each customer → 3 latest orders
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
Strengths: Reads only the rows needed per group.
Watch out: Slow without a supporting index; dialect differences.
Strengths: Portable and set-based.
Watch out: Ranks every row before filtering.
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?
Knowledge check
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.