Sub topic 4
LEFT JOIN LATERAL: keeping rows with no match
This chapter assumes you can read CROSS JOIN LATERAL queries, including the top-N-per-group pattern, and that you know how LEFT JOIN fills missing columns with NULL. It builds on the previous chapters and doesn't repeat them. The goal here is to keep every row from the left side of a lateral join, including rows where the lateral subquery returns nothing.
Sample data
The examples use three customers. Ada has four orders, Ben has one, and Cara has none.
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 date NOT NULL
);
INSERT INTO customers (id, name) VALUES
(1, 'Ada'), (2, 'Ben'), (3, 'Cara');
INSERT INTO orders (id, customer_id, total, created_at) VALUES
(10, 1, 50.00, '2026-01-05'),
(11, 1, 20.00, '2026-02-10'),
(12, 1, 75.00, '2026-03-01'),
(13, 1, 30.00, '2026-04-15'),
(14, 2, 15.00, '2026-02-20');What CROSS JOIN LATERAL loses
A CROSS JOIN LATERAL pairs each left row with every row its subquery returns. If the subquery returns zero rows for a left row, there is nothing to pair it with, so that left row disappears from the result. This is the same behavior as an INNER JOIN.
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;| id | name | order_id | total |
|---|---|---|---|
| 1 | Ada | 13 | 30.00 |
| 1 | Ada | 12 | 75.00 |
| 1 | Ada | 11 | 20.00 |
| 2 | Ben | 14 | 15.00 |
Cara is missing. For a report that lists every customer with their latest orders, that is a bug, and it is easy to miss because no error is raised.
The LEFT JOIN LATERAL form
Switch to LEFT JOIN LATERAL and add ON true:
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o ON true
ORDER BY c.id, o.id DESC;| id | name | order_id | total |
|---|---|---|---|
| 1 | Ada | 13 | 30.00 |
| 1 | Ada | 12 | 75.00 |
| 1 | Ada | 11 | 20.00 |
| 2 | Ben | 14 | 15.00 |
| 3 | Cara | NULL | NULL |
Cara now appears once, with NULL in every column that comes from the lateral subquery. A left row with matches produces one output row per match. A left row with no matches produces exactly one output row.
Conceptually the subquery runs once per left row, as with CROSS JOIN LATERAL. The planner may choose another strategy, but the result must be the same as this per-row model.
Why ON true is required
Every LEFT JOIN needs a join condition, and the syntax has no way to omit it. A CROSS JOIN has no ON clause because it has no condition at all. With LEFT JOIN LATERAL, the correlation already happens inside the subquery through WHERE orders.customer_id = c.id. The join itself has nothing left to test, so you write ON true, a condition that every pair satisfies.
If you leave ON off, PostgreSQL reports a syntax error. The fix is to add ON true, not to remove LEFT.
ON true is the usual form, but ON can hold a real condition. That changes the result, and the rest of this chapter explains how.
Aggregates: LEFT versus CROSS
A subquery that contains an aggregate with no GROUP BY always returns exactly one row, even when its input is empty. That row is produced for every left row, so no customer is dropped. LEFT and CROSS give the same row set in this case.
SELECT c.id,
c.name,
s.order_count,
coalesce(s.revenue, 0) AS revenue
FROM customers c
LEFT JOIN LATERAL (
SELECT count(*) AS order_count,
sum(total) AS revenue
FROM orders
WHERE orders.customer_id = c.id
) AS s ON true
ORDER BY c.id;| id | name | order_count | revenue |
|---|---|---|---|
| 1 | Ada | 4 | 175.00 |
| 2 | Ben | 1 | 15.00 |
| 3 | Cara | 0 | 0 |
Two details are worth noting:
count(*)inside the subquery returns0for Cara. Counts never come back asNULL.sum(total)over no rows returnsNULL, socoalescesupplies the zero.
Compare this with an ordinary LEFT JOIN orders followed by an outer count(*). There, Cara's single NULL-filled row would count as 1. Counting happens before the join here, so the count is correct.
Writing LEFT JOIN LATERAL ... ON true for an always-one-row subquery is still a good habit. It stays correct if someone later adds a HAVING clause or a GROUP BY that could make the subquery return no rows.
Telling "no match" apart from NULL data
After a left join, a NULL in o.total can mean two things: no order existed, or an order existed and its total is NULL. In the sample schema total is NOT NULL, so the ambiguity doesn't arise. In real schemas it often does.
Add a marker column inside the subquery. It is non-null whenever a row was produced:
SELECT c.id, c.name, o.id AS order_id, o.matched
FROM customers c
LEFT JOIN LATERAL (
SELECT id, true AS matched
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o ON true
ORDER BY c.id;o.matched is true when an order was found and NULL when none was. You can also test a column you know is never null in the source table, such as the primary key o.id.
Where you put a filter changes the result
There are three places to put a condition, and they behave differently. The example filter is total > 40, applied to the latest-three-orders query.
In the outer WHERE
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 3
) AS o ON true
WHERE o.total > 40
ORDER BY c.id;Only Ada's order 12 survives. WHERE runs after the join, and for Cara o.total is NULL, so NULL > 40 is not true and her row is removed. Ben's order fails the test and is removed too. The query is now effectively an inner join, and the LEFT has no effect. This is the most common mistake with left joins in general.
In the ON clause
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT 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 > 40
ORDER BY c.id;| id | name | order_id | total |
|---|---|---|---|
| 1 | Ada | 12 | 75.00 |
| 2 | Ben | NULL | NULL |
| 3 | Cara | NULL | NULL |
The subquery still picks Ada's three latest orders (13, 12, 11). The ON condition then keeps only order 12. Ben's one order fails the condition, so Ben is kept with NULL columns. Every customer appears.
Inside the subquery
SELECT c.id, c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
AND total > 40
ORDER BY created_at DESC
LIMIT 3
) AS o ON true
ORDER BY c.id, o.id DESC;| id | name | order_id | total |
|---|---|---|---|
| 1 | Ada | 12 | 75.00 |
| 1 | Ada | 10 | 50.00 |
| 2 | Ben | NULL | NULL |
| 3 | Cara | NULL | NULL |
Here the filter runs before LIMIT, so the subquery returns the latest three orders that are over 40. For Ada those are orders 12 and 10. The ON version asked for the latest three orders and then discarded some.
| Filter location | Applied | Keeps rows with no match? | Meaning |
|---|---|---|---|
| Outer `WHERE` on lateral columns | After the join | No | Turns the query into an inner join |
| `ON` clause | During the join, after `LIMIT` | Yes | Filters the rows the subquery returned |
| Inside the subquery | Before `LIMIT` | Yes | Filters which rows the subquery considers |
Finding rows with no match
Because unmatched rows carry NULL in the lateral columns, you can select exactly those rows with an IS NULL test on a column that is never null in the source table:
SELECT c.id, c.name
FROM customers c
LEFT JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
LIMIT 1
) AS o ON true
WHERE o.id IS NULL;This returns Cara. The LIMIT 1 lets the subquery stop at the first order it finds. The same result is more directly expressed as WHERE NOT EXISTS (SELECT 1 FROM orders WHERE orders.customer_id = c.id). Use NOT EXISTS when it is all you need. Reach for the lateral form when you also want columns from the matched row in the same query.
Chaining several lateral joins
Each lateral item can refer to any item listed before it, including earlier lateral subqueries. When you chain left joins, keep every link as LEFT JOIN LATERAL. A single CROSS JOIN LATERAL in the middle removes any row for which that step returns nothing, and a later LEFT cannot bring it back.
SELECT c.name, latest.id AS latest_order_id, big.id AS biggest_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 latest ON true
LEFT JOIN LATERAL (
SELECT id
FROM orders
WHERE orders.customer_id = c.id
ORDER BY total DESC
LIMIT 1
) AS big ON true
ORDER BY c.id;Each customer appears once. Cara has NULL in both columns.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Syntax error after the subquery alias | `ON` omitted on a `LEFT JOIN LATERAL` | Add `ON true` |
| Customers with no orders are missing | `CROSS JOIN LATERAL`, or an outer `WHERE` on lateral columns | Use `LEFT JOIN LATERAL ... ON true` and move filters into the subquery or `ON` |
| A `NULL` row appears but you can't tell why | The column is nullable in the source table | Add a marker column such as `true AS matched`, or test the primary key |
| Totals show `NULL` instead of `0` | `sum` over zero rows is `NULL` | Wrap with `coalesce(..., 0)` |
| An outer `count(*)` reports 1 for unmatched rows | The unmatched row still exists, so it is counted | Count a lateral column such as `count(o.id)`, or aggregate inside the subquery |
| Duplicate left rows | The subquery returns several rows per left row | Add `LIMIT`, aggregate, or accept one row per match |
Performance note
LEFT JOIN LATERAL costs about the same as the CROSS version. The extra work is only emitting a NULL row when the subquery is empty. The per-row lookup is what matters, and an index on orders (customer_id, created_at DESC) serves it. A later chapter covers reading the plan.
Exercises
Exercise
A query uses FROM customers c LEFT JOIN LATERAL (SELECT id, total FROM orders WHERE orders.customer_id = c.id ORDER BY created_at DESC LIMIT 3) o ON true WHERE o.total > 0. Every total in the table is positive, yet Cara (no orders) is missing from the result. Why, and how do you fix it?
Show answer
The outer WHERE runs after the join. For Cara, o.total is NULL, and NULL > 0 is not true, so her row is removed. Remove the WHERE condition (all totals are positive, so it is redundant), or move any real filter into the subquery's WHERE or into the ON clause. If you only want to exclude orders that are not positive, put AND total > 0 inside the subquery.
Exercise
Write a query that returns every customer with the number of orders and the date of their most recent order, showing 0 and NULL for customers with no orders. Which join form do you use and why?
Show answer
SELECT c.id, c.name, s.ordercount, s.lastorder FROM customers c LEFT JOIN LATERAL (SELECT count(*) AS ordercount, max(createdat) AS lastorder FROM orders WHERE orders.customerid = c.id) s ON true ORDER BY c.id; The aggregate subquery always returns one row, with count 0 and max NULL for Cara. LEFT JOIN LATERAL ... ON true is the safe form because it keeps customers even if the subquery is later changed so that it can return no rows.
Exercise
Using the sample data, what does the query with ON o.total > 40 return for Ben, and what would it return if the same condition were written inside the subquery's WHERE clause?
Show answer
In both cases Ben appears once with NULL in order_id and total, because his only order (total 15.00) does not satisfy total > 40. The two forms differ for customers with more than three orders. Ada gets only order 12 with the ON form, because the three latest orders are chosen first. She gets orders 12 and 10 with the subquery form, because the filter runs before LIMIT 3.