Sub topic 1
The problem: subqueries in FROM cannot see their neighbours
Prerequisites
This chapter assumes you know basic SELECT, WHERE, ORDER BY, and LIMIT, plus INNER JOIN and LEFT JOIN. You should also be comfortable with table aliases and with subqueries in the FROM clause.
Why a plain FROM subquery fails
A subquery in FROM is built as its own result set. By default, it cannot refer to columns of other tables in the same FROM clause. This query tries to use c.id inside the subquery:
-- Fails: the subquery cannot refer to c
SELECT c.id, o.total
FROM customers c
JOIN (SELECT total FROM orders WHERE orders.customer_id = c.id) o ON true;
-- ERROR: invalid reference to FROM-clause entry for table "c"What LATERAL does
The LATERAL keyword tells PostgreSQL that a subquery or function in FROM may refer to items listed before it. PostgreSQL then evaluates the subquery once for each row on the left side, much like a correlated subquery in the SELECT list.
CROSS JOIN LATERAL and ON true
This query returns the three newest orders for each customer:
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o;JOIN LATERAL ... ON true is equivalent. The ON true condition keeps every combined row, so it works like a cross join with a per-row subquery.
Exercise
Why does the query with a plain subquery in FROM fail, and what keyword fixes it?
Show answer
The subquery refers to c.id, which belongs to another FROM item, and a plain FROM subquery cannot see sibling items. Adding LATERAL before the subquery allows that reference, so the query becomes JOIN LATERAL (...) ON true or CROSS JOIN LATERAL (...).