Sub topic 3
CROSS JOIN LATERAL and ON true
This chapter assumes you can write SELECT, WHERE, ORDER BY and LIMIT, and that you know INNER JOIN, LEFT JOIN, subqueries in FROM, and table aliases. It also assumes you have met the idea from the previous chapters: an ordinary subquery in FROM cannot see the other tables in the same FROM clause, and LATERAL removes that limit.
Here you will learn the two spellings of an inner lateral join, CROSS JOIN LATERAL and JOIN LATERAL ... ON true. You will see what each one returns, how rows multiply or disappear, and which errors you will hit most often.
The sample data
The examples use two small tables. Run this once to follow along.
CREATE TABLE customers (
id int PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id int PRIMARY KEY,
customer_id int NOT NULL REFERENCES customers (id),
total numeric(10, 2) NOT NULL,
created_at timestamptz NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ada'),
(2, 'Bo'),
(3, 'Cy');
INSERT INTO orders (id, customer_id, total, created_at) VALUES
(1, 1, 20.00, '2026-01-01'),
(2, 1, 35.00, '2026-01-05'),
(3, 1, 15.50, '2026-01-09'),
(4, 1, 50.00, '2026-01-12'),
(5, 2, 10.00, '2026-01-03'),
(6, 2, 99.00, '2026-01-10');Ada has four orders, Bo has two, and Cy has none. Cy matters in this chapter because of what happens to customers with no matching rows.
The core pattern
A lateral join has a left side and a right side. The right side is a subquery or function that refers to columns of the left side. PostgreSQL evaluates the right side once for each left row, with that row's values filled in. Then it combines the left row with every row the right side returned.
This query returns each customer's three most recent orders.
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
ORDER BY c.id, o.id DESC;The result has five rows.
| id | name | order_id | total |
|---|---|---|---|
| 1 | Ada | 4 | 50.00 |
| 1 | Ada | 3 | 15.50 |
| 1 | Ada | 2 | 35.00 |
| 2 | Bo | 6 | 99.00 |
| 2 | Bo | 5 | 10.00 |
Three things happen here.
- The condition
orders.customer_id = c.idrefers toc, a table on the left. This reference is only legal because of the wordLATERAL. ORDER BY created_at DESC LIMIT 3runs inside the subquery, so it applies separately for each customer. A plainLIMIT 3on the whole query would return three rows in total.- Cy is missing from the result. The subquery returned no rows for Cy, and a cross join of one row with zero rows is zero rows.
The final ORDER BY in the query is only there to make the output order predictable. A join does not promise any row order.
This per-row model is the logical behaviour. The planner is free to choose a different physical plan as long as the result is the same.
Three spellings of the same join
PostgreSQL accepts several forms of an inner lateral join. They return the same rows.
-- 1. Explicit cross join
SELECT c.id, o.id AS order_id
FROM customers c
CROSS JOIN LATERAL (
SELECT id FROM orders WHERE orders.customer_id = c.id
) AS o;
-- 2. Inner join with a condition that is always true
SELECT c.id, o.id AS order_id
FROM customers c
JOIN LATERAL (
SELECT id FROM orders WHERE orders.customer_id = c.id
) AS o ON true;
-- 3. Comma form
SELECT c.id, o.id AS order_id
FROM customers c,
LATERAL (
SELECT id FROM orders WHERE orders.customer_id = c.id
) AS o;Forms 1 and 3 are identical in meaning, because a comma between FROM items is a cross join. Form 2 is an inner join whose join condition never rejects anything.
Why would you write ON true? An INNER JOIN requires an ON or USING clause, and the correlation already lives inside the subquery, so there is nothing left for ON to say. true satisfies the grammar. You will also see ON true in LEFT JOIN LATERAL, where the clause is required in the same way. Writing JOIN LATERAL ... ON true for inner joins makes the two forms look alike and makes it easy to switch between them later.
Choose one spelling and use it consistently across a codebase. Many teams prefer CROSS JOIN LATERAL for inner behaviour because it states that the join condition is inside the subquery. The comma form is shorter but easy to misread, especially once other joins follow it.
Rows multiply and rows vanish
The right side can return any number of rows for each left row, and the output follows that number.
| Right side returns | Output for that left row |
|---|---|
| 0 rows | no rows, so the left row disappears |
| 1 row | one row, the left columns plus the right columns |
| N rows | N rows, the left columns repeated on each |
The first line is the one that surprises people. With CROSS JOIN LATERAL, a left row with no right-side match is dropped, exactly as with an INNER JOIN. If you need those rows to survive, you need LEFT JOIN LATERAL ... ON true, which the next chapter covers.
The repeated left columns also mean that aggregating afterwards can double count. If you join customers to their orders and then sum() a customer column, each customer value is added once per order.
A subquery that always returns one row
An aggregate query with no GROUP BY always returns exactly one row, even when it reads zero input rows. That makes it a safe lateral subquery when you want every left row to survive.
SELECT c.id, c.name, s.order_count, s.revenue
FROM customers c
CROSS JOIN LATERAL (
SELECT count(*) AS order_count,
coalesce(sum(total), 0) AS revenue
FROM orders
WHERE orders.customer_id = c.id
) AS s
ORDER BY c.id;| id | name | order_count | revenue |
|---|---|---|---|
| 1 | Ada | 4 | 120.50 |
| 2 | Bo | 2 | 109.00 |
| 3 | Cy | 0 | 0 |
Cy appears here because the subquery returned one row for Cy: a count of 0 and a sum of NULL, which coalesce turns into 0. The cross join did not change its behaviour. The subquery simply never returned zero rows.
This is the first real decision point. The shape of the right side decides whether the join keeps all left rows.
- A plain
SELECT ... WHEREcan return zero rows, so left rows can vanish. - An aggregate without
GROUP BYreturns one row, so left rows always survive. - An aggregate with
GROUP BYreturns one row per group, which can again be zero.
Filtering with ON
For an inner JOIN LATERAL, the ON clause does not have to be true. You can put a real condition there. It is applied to the rows the subquery returned, after the per-row evaluation.
SELECT c.id, c.name, 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 3
) AS o ON o.total > 30
ORDER BY c.id, o.id DESC;This takes each customer's three most recent orders first, then keeps only those over 30. The result is Ada's orders 4 (50.00) and 2 (35.00), and Bo's order 6 (99.00).
Order matters here. The LIMIT 3 ran before the ON filter. If you want the three most recent orders among those over 30, put AND total > 30 in the subquery's WHERE clause instead. Mixing up these two places is a common source of wrong answers that look plausible.
Common errors
Missing LATERAL. Without the keyword, PostgreSQL rejects the reference to the left table.
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"
-- HINT: There is an entry for table "c", but it cannot be referenced from this part of the query.The fix is to add LATERAL before the subquery.
Referencing a table that comes later. A lateral reference may only point at FROM items to its left. If you write the subquery first and customers second, the reference fails, because the lateral item has not yet seen the later table.
JOIN LATERAL with no ON. This is a syntax error, because JOIN on its own is an inner join and needs a condition. Add ON true, or use CROSS JOIN LATERAL.
Forgetting that the subquery needs an alias. A subquery in FROM must have an alias, as in AS o. Without it PostgreSQL reports that a subquery in FROM must have an alias.
Ambiguous column names. If the subquery selects a column called id, and the outer query also has c.id, you must qualify them in the select list (o.id, c.id) and rename with AS if you need both in the output.
Does LATERAL really run the subquery per row?
Logically, yes. Physically, not always. PostgreSQL can often flatten a simple lateral subquery into an ordinary join. When it cannot, which is the usual case for subqueries containing LIMIT, it uses a nested loop and re-executes the subquery for each outer row, passing the outer values in as parameters.
You can see this in EXPLAIN output as a Nested Loop node whose inner side shows the filter (customer_id = c.id) as an index condition or a filter. The performance chapter shows how to read it and which index to create. For now, remember the cost model: the number of outer rows times the cost of one subquery run. A lateral join over a million customers runs the subquery a million times unless the planner finds something cleverer.
Summary of the forms
| Form | Behaviour with 0 matching rows | Typical use |
|---|---|---|
| `CROSS JOIN LATERAL (...) AS x` | left row dropped | inner semantics, no extra condition |
| `JOIN LATERAL (...) AS x ON true` | left row dropped | same, written as a join |
| `JOIN LATERAL (...) AS x ON cond` | left row dropped, rows failing `cond` removed | filtering the subquery result |
| `LEFT JOIN LATERAL (...) AS x ON true` | left row kept, right columns NULL | keeping all left rows |
Exercise
Using the sample tables, write a query that returns each customer's single most expensive order (id and total) using CROSS JOIN LATERAL. Which customers appear in the result, and why does Cy not?
Show answer
SELECT c.id, c.name, o.id AS orderid, o.total FROM customers c CROSS JOIN LATERAL (SELECT id, total FROM orders WHERE orders.customerid = c.id ORDER BY total DESC LIMIT 1) AS o ORDER BY c.id; The result contains Ada (order 4, 50.00) and Bo (order 6, 99.00). Cy has no orders, so the subquery returns zero rows for Cy, and a cross join with zero rows produces no output row for that customer.
Exercise
The query below fails. Explain why, then give two different corrected versions. SELECT c.id, o.total FROM customers c JOIN (SELECT total FROM orders WHERE orders.customer_id = c.id) o ON true;
Show answer
A subquery in FROM cannot refer to c unless it is marked LATERAL, so PostgreSQL reports an invalid reference to FROM-clause entry for table "c". Fix 1: SELECT c.id, o.total FROM customers c JOIN LATERAL (SELECT total FROM orders WHERE orders.customerid = c.id) o ON true; Fix 2: SELECT c.id, o.total FROM customers c CROSS JOIN LATERAL (SELECT total FROM orders WHERE orders.customerid = c.id) o; Both return the same rows, and customers without orders are dropped.
Exercise
A colleague writes JOIN LATERAL (SELECT id, total FROM orders WHERE orders.customerid = c.id ORDER BY createdat DESC LIMIT 3) o ON o.total > 30 and expects the three most recent orders that are over 30. Is that what the query returns? How do you change it?
Show answer
No. The LIMIT 3 runs inside the subquery first, so it picks the three most recent orders, and the ON condition then removes those that are 30 or less. A customer can get fewer than three rows even if they have more large orders. To get the three most recent orders over 30, move the condition into the subquery: WHERE orders.customer_id = c.id AND total > 30, and use ON true.