Sub topic 2
What LATERAL Does
What you need before this chapter
This chapter assumes you can write SELECT queries with WHERE, ORDER BY and LIMIT. It also assumes you know how INNER JOIN and LEFT JOIN behave, how to put a subquery in the FROM clause, and how to give tables aliases. It uses PostgreSQL 12 or later, but LATERAL has been available since version 9.3.
The examples use two small tables. Run this setup once.
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, 'Ben'), (3, 'Cleo');
INSERT INTO orders (id, customer_id, total, created_at) VALUES
(101, 1, 40.00, '2026-01-05'),
(102, 1, 15.50, '2026-02-10'),
(103, 1, 99.99, '2026-03-01'),
(104, 2, 20.00, '2026-02-20');Ada has three orders, Ben has one, and Cleo has none.
The scoping rule that LATERAL changes
Items in a FROM clause are normally independent of each other. The planner may read them in any order, so a subquery in FROM is not allowed to see its siblings. This query fails:
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"The subquery needs c.id, but c is a sibling FROM item. The subquery has to be a self-contained query that could run on its own.
LATERAL lifts this restriction. Writing LATERAL before a subquery tells PostgreSQL that the subquery may refer to columns of FROM items that appear before it. The right-hand side then depends on the left-hand side, so it cannot be computed once for the whole query.
The mental model: a loop over the left side
Read a lateral item as a loop:
- Take one row from the items on the left.
- Substitute that row's values for the outer references inside the lateral subquery.
- Run the subquery and collect the rows it returns.
- Combine the left row with each returned row, then move to the next left row.
The loop is a model of the result, not a promise about execution. PostgreSQL only has to return what the loop would return, and it can use other plans when they give the same rows. A later section covers this.
A first working example
This query returns each customer's latest order. It uses the comma form of a join, FROM a, LATERAL (...), which is equivalent to a cross join. The next chapter covers the explicit CROSS JOIN LATERAL and LEFT JOIN LATERAL forms.
SELECT c.name, o.id AS order_id, o.total
FROM customers c,
LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
ORDER BY created_at DESC
LIMIT 1
) AS o
ORDER BY c.id;The result is:
| name | order_id | total |
|---|---|---|
| Ada | 103 | 99.99 |
| Ben | 104 | 20.00 |
The LIMIT 1 applies to each customer separately. This is what a plain subquery cannot do, because a plain subquery would apply LIMIT 1 once to the whole table. Cleo does not appear because her subquery returned no rows, and a cross join with an empty set produces nothing.
Syntax details
LATERAL can precede two kinds of FROM item:
- A subquery in parentheses, with an alias.
- A function call that returns rows, such as
generate_series,unnestorjsonb_array_elements.
It cannot precede an ordinary table name. A plain table has no expressions that could refer to another item, so the keyword would have no meaning there.
Put an alias on every lateral subquery. PostgreSQL 16 and later accept an unaliased subquery in FROM, but older versions reject it, and an alias is needed to refer to the columns anyway.
Functions are implicitly lateral
For function calls, the keyword is optional. PostgreSQL treats a function in FROM as lateral automatically when its arguments refer to earlier items. These two queries are identical:
SELECT c.name, g.n
FROM customers c, generate_series(1, c.id) AS g(n);
SELECT c.name, g.n
FROM customers c, LATERAL generate_series(1, c.id) AS g(n);Ada gets one row, Ben gets two, and Cleo gets three, because the function's upper bound is each customer's id. Writing LATERAL anyway makes the dependency visible to the next reader. Subqueries get no such shortcut, and leaving the keyword out produces the error shown earlier.
What a lateral item can see
A lateral item can reference columns from FROM items that appear before it in the same FROM list. The order matters.
-- Fails: c is to the right of the lateral item
SELECT *
FROM LATERAL (SELECT c.id AS cid) AS x,
customers c;PostgreSQL reports an invalid reference to the entry for c, and its hint says the table exists but cannot be referenced from this part of the query. Move customers c to the left of the lateral item and the query works.
A lateral item can also see columns of a query that encloses it, as any correlated subquery can. LATERAL adds visibility of the siblings to its left.
Chaining lateral items
Each lateral item can see everything to its left, including earlier lateral items. This lets you build a result in steps:
SELECT c.name, l.last_at, o.id AS order_id, o.total
FROM customers c,
LATERAL (
SELECT max(created_at) AS last_at
FROM orders
WHERE orders.customer_id = c.id
) AS l,
LATERAL (
SELECT id, total
FROM orders
WHERE orders.customer_id = c.id
AND orders.created_at = l.last_at
) AS o;The first lateral item finds the newest order date for the customer. The second uses l.last_at to fetch that order. This particular query is more complicated than the ORDER BY ... LIMIT 1 version, but it shows the visibility rule: o can see both c and l.
An aggregate without GROUP BY always returns exactly one row, even over zero input rows. For Cleo, the first lateral item returns one row with last_at as NULL, and the second returns none. She is still dropped from the result, but for a different reason than before.
Name resolution inside the subquery
Inside a lateral subquery, an unqualified column name resolves to the subquery's own tables first. Only if no inner table has that column does PostgreSQL look outward. This produces quiet bugs:
-- Wrong: both ids refer to orders.id, so the condition compares a column to itself
SELECT c.name, o.total
FROM customers c,
LATERAL (SELECT total FROM orders WHERE id = id) AS o;Always qualify outer references (c.id) and preferably inner ones too (orders.customer_id). A qualified name is never ambiguous, and it shows which side of the join a column comes from.
LATERAL compared with a plain subquery
| Property | Plain subquery in FROM | LATERAL subquery |
|---|---|---|
| Can reference sibling `FROM` items | No | Yes, those listed before it |
| Logically evaluated | Once | Once per row of the items on its left |
| `LIMIT` and `ORDER BY` apply | To the whole subquery result | To each outer row's result |
| Can be written in any `FROM` position | Yes | Only after the items it references |
| Keyword needed for functions | Not applicable | Optional |
How PostgreSQL actually runs it
The per-row loop is how you should reason about the meaning of the query. The planner is free to choose a different strategy when the result is the same.
- A lateral subquery with
LIMIT,ORDER BYplusLIMIT, or other constructs that must be evaluated per outer row is usually run as the inner side of a nested loop. The outer value is passed in as a parameter each time. - A simple lateral subquery, such as a plain filter with no
LIMIT, can sometimes be flattened into an ordinary join. The query then runs as a hash join or merge join instead of a loop. - A lateral function call is run by a function scan node, once for each outer row.
You can check which plan was chosen with EXPLAIN. For the latest-order query above, a nested loop whose inner side shows loops= equal to the number of customers confirms the per-row evaluation. The performance chapter covers how to read this output and which indexes help.
Common mistakes
- Omitting the keyword on a subquery. The error is "invalid reference to FROM-clause entry". Add
LATERALbefore the subquery. - Referencing an item to the right. Reorder the
FROMlist so the referenced table comes first. - Unqualified column names. An inner column of the same name shadows the outer one. Qualify every reference.
- Expecting rows for customers with no match. With the comma or
CROSS JOINform, an empty lateral result removes the outer row. The next two chapters cover how to keep those rows. - Using volatile functions without noticing. A lateral item containing
random()ornow()-like volatile calls is evaluated per outer row, so each row can get a different value. This is often the intent, but be aware of it.
Summary of the working model
LATERAL makes a subquery or function in FROM depend on the items to its left. Logically, it runs once per left row with that row's values substituted in. Because it runs per row, clauses such as ORDER BY and LIMIT inside it work per outer row. This is the property the following chapters use for top-N-per-group queries, row expansion and reusing computed values.
Exercise
A colleague writes SELECT c.name, o.total FROM customers c, (SELECT total FROM orders WHERE orders.customer_id = c.id ORDER BY created_at DESC LIMIT 1) AS o; and gets an "invalid reference to FROM-clause entry" error. What one-word change fixes it, where does it go, and why does it fix the error?
Show answer
Add LATERAL before the subquery: FROM customers c, LATERAL (SELECT ...) AS o. Without it, the subquery is evaluated independently of c and cannot refer to c.id. With LATERAL, PostgreSQL allows references to FROM items to its left and evaluates the subquery once per customer row, so the LIMIT 1 applies per customer.
Exercise
In the query SELECT c.name, g.n FROM customers c, generate_series(1, c.id) AS g(n); there is no LATERAL keyword, yet it works. Why? How many rows does it return for the sample data, and which customer's rows are returned most often?
Show answer
A function call in FROM is treated as lateral automatically when its arguments refer to earlier FROM items, so the keyword is optional for functions. It returns 1 + 2 + 3 = 6 rows: Ada gets 1 row, Ben gets 2, and Cleo gets 3. Cleo appears most often because her id is 3 and the series runs from 1 to that value.
Exercise
Inside LATERAL (SELECT total FROM orders WHERE id = id), the author meant to compare orders.id with the outer customer's id. What actually happens, and how should the query be written?
Show answer
Unqualified names resolve to the subquery's own tables first, so both id references mean orders.id. The condition compares a column to itself and is true for every non-null row, so the intended filter never happens. Qualify the references, for example WHERE orders.customer_id = c.id, so each name points to a specific table.