Video in progress
What is a `LATERAL` JOIN and when do you need it?
LATERAL lets a subquery see the columns of the tables to its left, so the subquery runs for each outer row with a "parameter". It's handy in "top-N per row" queries, like each customer's last 3 orders.
📖 Answer
A regular subquery in FROM can't refer to the outer table. With LATERAL it can:
SELECT c.id, c.name, o.id AS order_id, o.created_at
FROM customers c
CROSS JOIN LATERAL (
SELECT id, created_at
FROM orders
WHERE orders.customer_id = c.id -- refers to c, thanks to LATERAL
ORDER BY created_at DESC
LIMIT 3
) o
WHERE c.city = 'Toshkent';
With an orders(customer_id, created_at DESC) index, only 3 rows are read from the index per customer. When there are few customers and many orders, this is much faster than numbering the whole table with ROW_NUMBER().
If you want customers with no orders to stay in the result, write LEFT JOIN LATERAL (...) o ON true.
Another use is with set-returning functions: CROSS JOIN LATERAL jsonb_array_elements(doc->'items') AS item. In fact functions in FROM are automatically lateral, so this works even without writing the keyword.
Sign up to mark studied questions and save your progress.