Sub topic 9
Which joins allow LATERAL references
This chapter covers which join types let a LATERAL item refer to the tables beside it, and which ones reject the reference. I assume you can write CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON true, and that you know how inner and outer joins behave. The examples use two tables:
customers(id, name)orders(id, customer_id, total, created_at)
The rule in one sentence
A LATERAL item can see only the FROM items to its left. When it sits in a join tree, it can also see the left input of the join it is the right input of. The reference is allowed only if the combining join is an inner join (including CROSS JOIN and the comma) or a LEFT JOIN.
Everything else in this chapter follows from that sentence. First, why the restriction exists. Second, how to read the errors when you break it. Third, how to rewrite queries so they work.
Why order and join type matter
A lateral item is evaluated once per row of whatever is on its left. That gives it a fixed dependency direction: the left side must be computed first, and the right side is a function of each left row.
Each join type promises something about which rows survive:
- An inner join keeps only pairs of rows that match. A left row with no lateral rows disappears. The executor can loop over the left rows and run the right side for each one.
- A
LEFT JOINkeeps every left row. If the lateral side returns nothing, the left row is kept with NULLs. The same loop works, with one extra rule for the empty case. - A
RIGHT JOINmust keep every right row. Here the right rows are produced from a left row, so there is no complete set of right rows to preserve. Rows that no left row produced do not exist. - A
FULL JOINhas the same problem, since it also preserves unmatched right rows.
PostgreSQL therefore rejects a lateral reference whenever the lateral item is the right input of a RIGHT or FULL join.
Allowed and rejected combinations
| Join form | Lateral item on the right can reference the left side? | Notes |
|---|---|---|
| `FROM a, LATERAL (...)` | Yes | Same as `CROSS JOIN LATERAL`. |
| `a CROSS JOIN LATERAL (...)` | Yes | The usual form. |
| `a [INNER] JOIN LATERAL (...) ON cond` | Yes | `cond` can filter the lateral rows. |
| `a LEFT JOIN LATERAL (...) ON cond` | Yes | Left rows with no match are kept with NULLs. |
| `a RIGHT JOIN LATERAL (...) ON cond` | No | Error. |
| `a FULL JOIN LATERAL (...) ON cond` | No | Error. |
| lateral item on the left of any join, referencing the right | No | The right side is not available yet. |
The sections below cover each rejected case.
The working forms
These three queries are equivalent. They return the latest order per customer, and customers without orders are dropped.
-- Comma form
SELECT c.id, o.id AS order_id
FROM customers c,
LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o;
-- CROSS JOIN form
SELECT c.id, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o;
-- INNER JOIN form with an always-true condition
SELECT c.id, o.id AS order_id
FROM customers c
JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o ON true;An inner JOIN LATERAL needs an ON clause, which is why you see ON true. The CROSS JOIN form has no ON clause and reads more cleanly when you have no condition to add.
With an inner join, the ON clause can do real work. This version returns only customers whose latest order is over 100:
SELECT c.id, o.id AS order_id, o.total
FROM customers c
JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o ON o.total > 100;Filtering in ON versus filtering in the subquery's WHERE gives different results. Putting total > 100 inside the subquery changes which order is the latest, because the filter runs before ORDER BY ... LIMIT 1. Putting it in ON filters after the latest order has been picked. For an inner join this decides which rows are considered. For a LEFT JOIN it also decides whether a customer is kept with NULLs.
Rejected: RIGHT and FULL joins
Try to reference the left side from the right input of a RIGHT JOIN:
SELECT c.id, o.id AS order_id
FROM customers c
RIGHT JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
) AS o ON true;PostgreSQL stops with an error that begins invalid reference to FROM-clause entry for table "c" and says the combining JOIN type must be INNER or LEFT for a LATERAL reference. FULL JOIN LATERAL fails the same way.
Usually the fix is to ask what you wanted to preserve:
- If you wanted every customer, even those without orders, use
LEFT JOIN LATERAL ... ON true. - If you wanted only customers that have orders, use
CROSS JOIN LATERALorJOIN LATERAL. - If you wanted every order, including orders with no customer, you do not need lateral. Start from
ordersandLEFT JOIN customers.
The remaining case is a full outer join that depends on per-row subqueries. You can build it by combining a LEFT JOIN LATERAL with a second query for the unmatched rows, joined by UNION ALL. That is rare, and a plain FULL JOIN between two independent subqueries usually makes the query simpler.
Rejected: referencing something to the right
A lateral item cannot look forward. This fails because c comes after the subquery:
SELECT c.id, x.id AS order_id
FROM LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
) AS x
CROSS JOIN customers c;The error mentions that there is an entry for table c, but that it cannot be referenced from this part of the query. The fix is to reorder the FROM list so that customers comes first. Order is meaningful with lateral items in a way it normally is not for inner joins.
Chaining lateral items
A later lateral item can reference any earlier item, including an earlier lateral item. This works left to right.
SELECT c.id,
l.id AS latest_order_id,
p.earlier_orders
FROM customers c
LEFT JOIN LATERAL (
SELECT id, created_at
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS l ON true
LEFT JOIN LATERAL (
SELECT count(*) AS earlier_orders
FROM orders AS o2
WHERE o2.customer_id = c.id
AND o2.created_at < l.created_at
) AS p ON true;The second lateral item references l, which is itself on the nullable side of a LEFT JOIN. This is allowed. For a customer with no orders, l.created_at is NULL, the comparison is never true, and count(*) returns 0. An aggregate without GROUP BY always returns exactly one row, so p has a row either way.
Keep that nullability in mind when you reference a lateral item from an outer join. The values arrive as NULL, and your later expressions must handle that.
Implicit LATERAL for functions
You do not need to write LATERAL in front of a function call in FROM. PostgreSQL treats it as lateral automatically.
SELECT t.n, g.i
FROM (VALUES (2), (3)) AS t(n)
CROSS JOIN generate_series(1, t.n) AS g(i);This returns two rows for n = 2 and three rows for n = 3. Writing CROSS JOIN LATERAL generate_series(1, t.n) means the same thing. Subqueries and VALUES lists are different: without the keyword they cannot see their neighbours, as you saw in the first chapter of this tutorial.
The same join-type rules apply to implicit lateral functions. RIGHT JOIN generate_series(1, t.n) fails for the same reason as the explicit form.
The ON clause has its own scope
A lateral reference is a different thing from a reference in an ON clause. An ON condition can only see the two inputs of its own join. Mixing commas and JOIN in one FROM list causes the classic error:
SELECT *
FROM customers c, orders o
JOIN LATERAL (SELECT 1 AS one) AS x ON x.one = c.id;JOIN binds more tightly than the comma, so the ON clause belongs to the join between o and x. Table c is outside it, and PostgreSQL reports an invalid reference to c. When you add lateral items, write explicit joins throughout the FROM list instead of mixing styles.
Reading the plan for join-type clues
The join type you wrote shows up in EXPLAIN as a nested loop. A lateral subquery is re-run for each outer row, so the planner chooses a nested loop with a parameterised inner side.
EXPLAIN
SELECT c.id, o.id AS order_id
FROM customers c
LEFT JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o ON true;Expect Nested Loop Left Join in the output, and for an inner or cross lateral join, Nested Loop. If the planner can flatten a lateral subquery into an ordinary join, which it can do for simple subqueries without LIMIT or aggregates, the plan may show a hash or merge join instead. Subqueries with LIMIT, as in these examples, stay as per-row nested loops.
Quick diagnosis table
| Symptom | Likely cause | Fix |
|---|---|---|
| `invalid reference to FROM-clause entry` on a subquery in FROM | Missing `LATERAL` keyword | Add `LATERAL` before the subquery. |
| Same error, mention of "JOIN type must be INNER or LEFT" | Lateral item on the right of `RIGHT` or `FULL` join | Use `LEFT JOIN LATERAL` or restructure. |
| Same error, referenced table is later in the list | Wrong FROM order | Move the referenced table before the lateral item. |
| Error in an `ON` clause that names a comma-listed table | `ON` sees only its own join inputs | Use explicit joins throughout. |
| Customers disappear from the result | Inner or cross lateral join with an empty lateral side | Use `LEFT JOIN LATERAL ... ON true`. |
| Unexpected NULLs in a later lateral item | It references a column from the nullable side of a `LEFT JOIN` | Handle NULL with `coalesce` or a condition. |
Exercise
A colleague writes FROM customers c FULL JOIN LATERAL (SELECT id FROM orders WHERE orders.customer_id = c.id) o ON true to list every customer and every order. PostgreSQL rejects it. Explain why, and write a query that returns every customer together with their orders, keeping customers who have none.
Show answer
A lateral item is computed from each left row, so the set of right rows exists only as a result of the left rows. A FULL (or RIGHT) join must preserve right rows that match no left row, and that set is not defined, so PostgreSQL only allows INNER and LEFT joins for lateral references. To keep customers with no orders, use a LEFT JOIN LATERAL: SELECT c.id, o.id AS orderid FROM customers c LEFT JOIN LATERAL (SELECT id FROM orders WHERE orders.customerid = c.id) AS o ON true; Because this is a plain correlated lookup with no LIMIT, a normal LEFT JOIN orders o ON o.customer_id = c.id gives the same result.
Exercise
Given FROM customers c LEFT JOIN LATERAL (SELECT created_at FROM orders WHERE customer_id = c.id ORDER BY created_at DESC LIMIT 1) l ON true, write a second lateral item p that counts that customer's orders older than l.created_at. What does p.n contain for a customer with no orders, and why?
Show answer
Add LEFT JOIN LATERAL (SELECT count(*) AS n FROM orders o2 WHERE o2.customer_id = c.id AND o2.created_at < l.created_at) AS p ON true. For a customer with no orders, l.created_at is NULL, so the comparison is never true and no rows are counted. An aggregate without GROUP BY always returns one row, so p.n is 0.