Sub topic 2
What LATERAL Does
Assume you know basic SELECT, WHERE, ORDER BY, LIMIT, joins, subqueries in FROM, and table aliases. This chapter explains the evaluation rule that makes a PostgreSQL LATERAL join useful.
The problem: subqueries in `FROM` cannot see their neighbours
A subquery in the FROM clause normally behaves like an independent table expression. It can see tables named inside itself, but it cannot refer to a table listed beside it:
-- Fails: the subquery cannot refer to c
SELECT c.id, o.total
FROM customers AS c
JOIN (
SELECT total
FROM orders
WHERE orders.customer_id = c.id
) AS o ON true;PostgreSQL rejects the reference to c because the subquery is not allowed to depend on a sibling FROM item. The database must plan the subquery as an independent relation.
This differs from a correlated subquery in a WHERE clause or select list. Those subqueries can refer to columns from an outer query level. A plain subquery in FROM does not get that behavior automatically.
What `LATERAL` changes
LATERAL gives a subquery or table function access to columns from FROM items that appear before it. PostgreSQL then evaluates the lateral item using each row from the preceding items.
The following query returns up to three recent orders for each customer:
SELECT c.id,
c.name,
o.id AS order_id,
o.total
FROM customers AS c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o;For each row in customers, PostgreSQL supplies that customer's id to the lateral subquery:
- Read one customer.
- Find orders whose
customer_idmatches that customer. - Sort those orders from newest to oldest.
- Keep at most three rows.
- Join those rows to the customer.
- Repeat for the next customer.
The result can contain several rows for one customer. If a customer has no matching orders, this CROSS JOIN LATERAL produces no row for that customer.
Reading the query structure
The keyword appears immediately before the dependent subquery:
CROSS JOIN LATERAL (
...
) AS oThe alias o names the rows produced by the subquery. As with other derived tables, PostgreSQL requires an alias in normal query style and the alias makes the selected columns easier to read.
The dependency flows from left to right. The subquery can refer to c because c appears before it:
A lateral item cannot refer forward to a table that appears later in the FROM clause. For example, placing customers AS c after the lateral subquery does not make c available to it.
`CROSS JOIN LATERAL` and `ON true`
CROSS JOIN LATERAL is appropriate when the outer row should appear only if the lateral item returns at least one row. It has no ON condition because the subquery itself contains the matching condition.
You can also write an inner lateral join with an always-true join condition:
SELECT c.id, o.order_id
FROM customers AS c
JOIN LATERAL (
SELECT id AS order_id
FROM orders
WHERE orders.customer_id = c.id
LIMIT 1
) AS o ON true;JOIN LATERAL ... ON true and CROSS JOIN LATERAL both use the lateral result as an inner join. The ON true condition means that every row returned by the lateral subquery is accepted. The actual relationship is expressed inside the subquery's WHERE clause.
The difference becomes important when you need to keep outer rows that have no match. That case uses LEFT JOIN LATERAL, which will be covered next.
The evaluation model
Think of a lateral query as a parameterized table expression. The columns from earlier FROM items act like parameters:
current customer row
|
v
orders WHERE customer_id = current customer.id
|
v
rows produced for that customerThis model explains why ORDER BY and LIMIT inside the lateral subquery apply separately to each outer row. In the earlier example, LIMIT 3 means three orders per customer, rather than three orders for the entire result.
Exercise
Why does the following query need LATERAL: SELECT c.id, x.value FROM customers AS c CROSS JOIN LATERAL (SELECT c.id * 10 AS value) AS x;
Show answer
The subquery refers to c.id from the preceding FROM item. LATERAL permits that per-row dependency, and x produces one value for each customer row.