Sub topic 2
LEFT JOIN LATERAL: keeping rows with no match
This chapter assumes you know SELECT, WHERE, ORDER BY, LIMIT, INNER and LEFT JOIN, subqueries in FROM, and table aliases.
A CROSS JOIN LATERAL drops any outer row whose lateral subquery returns nothing. A LEFT JOIN LATERAL keeps that outer row and fills the subquery columns with NULL. Use ON true with it, because the correlation already lives inside the subquery.
Assume customers(id, name) and orders(id, customer_id, total, created_at):
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o ON true
ORDER BY c.id;Top-N per group
The ORDER BY and LIMIT inside the lateral subquery apply to each outer row separately. The query above returns at most three orders per customer. Change LIMIT 3 to LIMIT 1 to get each customer's most recent order.
Set-returning functions in FROM
A set-returning function such as unnest can sit in a lateral join and use columns from earlier tables. WITH ORDINALITY adds a position number to each element.
SELECT p.id, u.tag, u.pos
FROM posts p
CROSS JOIN LATERAL unnest(p.tags) WITH ORDINALITY AS u(tag, pos);| Join form | Outer row with no lateral result |
|---|---|
| CROSS JOIN LATERAL | Row removed |
| LEFT JOIN LATERAL ... ON true | Row kept, lateral columns NULL |
Exercise
Using the customers and orders tables, how do you list every customer with their single most recent order, keeping customers who have no orders?
Show answer
LEFT JOIN LATERAL (SELECT id, total FROM orders WHERE orders.customerid = c.id ORDER BY createdat DESC LIMIT 1) AS o ON true