Part 06 / Topic 6 of 8
LATERAL: the per-row subquery join
A derived table in FROM cannot normally see the other FROM tables. LATERAL lifts exactly that restriction — the subquery may use the outer row, like a correlated subquery that returns whole rows. The canonical use: latest order per customer:
SELECT c.first_name, last_o.order_id, last_o.order_date
FROM customers AS c
CROSS JOIN LATERAL (
SELECT o.order_id, o.order_date
FROM orders AS o
WHERE o.customer_id = c.customer_id
ORDER BY o.order_date DESC
LIMIT 1
) AS last_o
ORDER BY c.customer_id;
first_name | order_id | order_date
------------+----------+------------
Asha | 7 | 2025-03-30
Ravi | 6 | 2025-03-18
Meera | 8 | 2025-04-12
John | 5 | 2025-03-05
Sara | 9 | 2025-04-20
(5 rows)
For each customer, the lateral subquery runs with their id, sorts their orders, keeps one. CROSS JOIN LATERAL drops customers whose subquery returns nothing (Vikram); LEFT JOIN LATERAL (...) ON true would keep them with NULLs.
"Top N per group" (each customer's last 3 orders: LIMIT 3) is LATERAL's home turf, alongside Part 2's DISTINCT ON (top 1 only) and next part's window functions — three tools, one family of questions.
🧪 Quick quiz — answer from memory, then check.
- What may a LATERAL subquery do that a plain FROM subquery may not?
- How do you keep customers with no orders in a LATERAL query?
Show the answers
- Reference columns of tables listed before it in the FROM clause.
LEFT JOIN LATERAL (...) ON true— unmatched outer rows survive with NULLs.
Exercise 6: Everyone's first order
What to do: Each customer's earliest order (id and date) — including the customer who has none, shown with blanks.
Sample output:
first_name | order_id | order_date
------------+----------+------------
Asha | 1 | 2025-01-10
Ravi | 2 | 2025-01-25
Meera | 4 | 2025-02-20
John | 5 | 2025-03-05
Sara | 9 | 2025-04-20
Vikram | |
(6 rows)
💡 Hint: LEFT JOIN LATERAL (... ORDER BY order_date LIMIT 1) ON true.
Show the solution to Exercise 6
-- Exercise 6: Everyone's first order
-- LEFT JOIN LATERAL ... ON true keeps Vikram, who has none.
SELECT c.first_name, first_o.order_id, first_o.order_date
FROM customers c
LEFT JOIN LATERAL (
SELECT o.order_id, o.order_date
FROM orders o
WHERE o.customer_id = c.customer_id
ORDER BY o.order_date
LIMIT 1
) AS first_o ON true
ORDER BY c.customer_id;