Sub topic 1
The problem: subqueries in FROM cannot see their neighbours
A subquery in the FROM clause looks like it should be able to use the other tables in that clause. In PostgreSQL it cannot, unless you mark it LATERAL. This chapter shows what fails, why the rule exists, and which workarounds exist. It also shows where those workarounds stop working, which is the reason LATERAL was added. Later chapters cover the fix in detail.
Prerequisites
This chapter assumes you already know:
- Basic
SELECT,WHERE,ORDER BYandLIMIT. INNER JOINandLEFT JOIN.- Subqueries in the
FROMclause (also called derived tables) and table aliases. - How to run SQL in
psqlor another PostgreSQL client. The examples use PostgreSQL 9.3 or later, the first version withLATERAL.
A sample schema
All examples use two small tables. You can paste this into any scratch database.
CREATE TABLE customers (
id integer PRIMARY KEY,
name text NOT NULL
);
CREATE TABLE orders (
id integer PRIMARY KEY,
customer_id integer 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, 'Cy');
INSERT INTO orders (id, customer_id, total, created_at) VALUES
(1, 1, 20.00, '2026-01-05'),
(2, 1, 35.00, '2026-02-10'),
(3, 1, 15.00, '2026-03-15'),
(4, 1, 50.00, '2026-04-20'),
(5, 2, 10.00, '2026-03-01');Ada has four orders, Ben has one, and Cy has none. Cy matters later, because customers with no matching rows behave differently in different join types.
The query we want
Suppose you want each customer's three most recent orders. The natural way to think about it is a loop: for each customer, find that customer's orders, sort them newest first, and keep three.
A first attempt follows that thinking. It puts the per-customer lookup in a subquery and joins it to customers:
SELECT c.id, o.total
FROM customers c
JOIN (SELECT total
FROM orders
WHERE orders.customer_id = c.id) o ON true;PostgreSQL rejects this:
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 wording of the hint depends on the PostgreSQL version. Some versions add that you must mark the subquery with LATERAL. The ERROR line is the same in all versions.
The subquery refers to c.id, and c is a perfectly good alias in the same FROM clause. The problem is where the reference appears, not whether c exists.
Why PostgreSQL rejects it
The rule is about scope, which means which names are visible from which part of a query.
- The
SELECTlist,WHERE,GROUP BY,ORDER BYand theONcondition of a join can all see every alias in theFROMclause. - A subquery written as a
FROMitem is different. It is treated as a complete, separate relation. It is built from its own innerFROMclause and nothing else. - Sibling
FROMitems do not see each other. The word "sibling" here means any two items in the sameFROMlist or on the two sides of the sameJOIN.
Left-to-right order does not change this. Even though customers c is written first, the subquery next to it cannot use c.
There are two practical reasons for the rule.
- Meaning. Without
LATERAL, a derived table is a plain relation with a fixed set of rows. You can run it on its own, copy it into a view, or reason about it without knowing what surrounds it. A reference toc.idwould make its contents depend on a row of another table, so it would no longer be one fixed set of rows. - Planning. The planner chooses the join order and join method itself. Two independent relations can be joined in either order, using a hash join, merge join or nested loop. A dependency between siblings removes some of those choices. Keeping the default independent keeps the planner free, and
LATERALmakes the dependency explicit when you want it.
The dotted line is the one that fails. Every arrow leaving the join is fine, because those clauses run after the join has combined both sides.
What does work: references to an outer query
The restriction applies only between siblings. A subquery in FROM can still refer to columns of a query that encloses it. This is called an outer reference.
SELECT c.id, c.name
FROM customers c
WHERE EXISTS (
SELECT 1
FROM (SELECT customer_id
FROM orders
WHERE orders.customer_id = c.id) AS o
);This is valid. The derived table o sits inside the EXISTS subquery, and the EXISTS subquery sits inside a WHERE clause that can see c. The reference to c.id goes up to an enclosing query level. It does not sideways to a sibling.
A useful test is to ask what the reference points at. If it points at an enclosing query, it is allowed. If it points at a table listed beside the subquery in the same FROM list, it is not allowed without LATERAL.
Workarounds and where they stop
Before LATERAL existed, people worked around the rule in three ways. Each of them handles a narrow case and fails once you need per-row logic.
Move the correlation into ON
If the subquery has no LIMIT and no aggregate, you can drop the reference from the subquery and put the condition in the join's ON clause. The ON clause can see both sides.
SELECT c.id, o.id AS order_id, o.total
FROM customers c
JOIN (SELECT id, customer_id, total FROM orders) o
ON o.customer_id = c.id
ORDER BY c.id, o.id;This works, but only because the subquery adds nothing the plain table would not. The problem appears when the subquery needs a LIMIT.
SELECT c.id, o.id AS order_id
FROM customers c
JOIN (SELECT id, customer_id
FROM orders
ORDER BY created_at DESC
LIMIT 3) o
ON o.customer_id = c.id
ORDER BY c.id, o.id DESC; id | order_id
----+----------
1 | 4
1 | 3
2 | 5
(3 rows)This runs without error, but the answer is wrong. The subquery is evaluated once, with no knowledge of any customer, so LIMIT 3 keeps the three newest orders in the whole table (orders 4, 3 and 5). The join then attaches them to customers. Ada's order 2 is missing, even though it is among her three newest. The limit applies to the table as a whole, not to each customer.
Scalar subquery in the SELECT list
A subquery in the SELECT list can see the outer row, so per-row logic works there:
SELECT c.id,
c.name,
(SELECT o.total
FROM orders o
WHERE o.customer_id = c.id
ORDER BY o.created_at DESC
LIMIT 1) AS latest_total
FROM customers c
ORDER BY c.id; id | name | latest_total
----+------+--------------
1 | Ada | 50.00
2 | Ben | 10.00
3 | Cy |
(3 rows)This gives the right answer, and Cy appears with NULL. The limits of this form are these:
- A scalar subquery must return exactly one column. If it names two columns, PostgreSQL raises
subquery must return only one column. - It must return at most one row. If it returns two or more, PostgreSQL raises
more than one row returned by a subquery used as an expression. - To fetch both the latest total and the latest date, you write two subqueries. Each one runs its own lookup, so you repeat the same filter and sort twice.
- You cannot return several rows per customer, so it cannot produce a "top three" list.
Join first, then filter
You can also join every order to its customer and then reduce the rows afterwards with a WHERE filter. This works when the filter is a simple comparison. It fails for "the first N per customer", because a WHERE clause cannot count rows within a group. The usual way to do that is a window function such as row_number(), which needs one more subquery layer. It is a valid technique and the lateral chapters compare it with LATERAL later.
The one-word fix
Adding the keyword LATERAL before the subquery changes its scope. The subquery may then refer to every FROM item listed before it, and it is evaluated once for each row of those items:
SELECT c.id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT total
FROM orders
WHERE orders.customer_id = c.id
) AS o;This is the failing query from earlier, with one keyword added and the join type chosen to match. The next chapters explain exactly how evaluation works, and how ORDER BY ... LIMIT 3 inside that subquery then produces the top-three-per-customer result the workarounds could not.
Some FROM items are lateral without the keyword. A set-returning function such as unnest can already use columns from tables to its left, so FROM posts p, unnest(p.tags) is valid as written. Only subqueries need the explicit keyword. A later chapter returns to this.
Common mistakes
| Symptom | Cause | Fix |
|---|---|---|
| `invalid reference to FROM-clause entry for table "c"` | A `FROM` subquery refers to a sibling alias | Add `LATERAL`, or move the condition into `ON` if no per-row `LIMIT` or aggregate is needed |
| Query runs, but "top N" rows belong to only a few groups | `LIMIT` placed in an uncorrelated subquery | Make the subquery lateral so the limit runs per row |
| `subquery must return only one column` | Scalar subquery used to fetch several columns | Use a lateral subquery in `FROM`, which can return many columns |
| `more than one row returned by a subquery used as an expression` | Scalar subquery used where several rows match | Add `LIMIT 1`, or use a lateral subquery |
| Reference to `c` works in one query but not in another | Outer query reference versus sibling reference | Check whether `c` is in an enclosing query or in the same `FROM` list |
Exercises
Exercise
A query contains FROM customers c JOIN (SELECT total FROM orders WHERE orders.customer_id = c.id) o ON true and PostgreSQL reports invalid reference to FROM-clause entry for table "c". Give two reasons the language does not let the subquery see c.
Show answer
A plain FROM subquery is a self-contained relation, so its rows must not depend on a row of another FROM item. Also, the planner is free to join independent relations in any order and with any method, and a reference between siblings would remove that freedom. LATERAL is the explicit opt-in for the dependency.
Exercise
Using the sample data, the query SELECT c.id, o.id AS order_id FROM customers c JOIN (SELECT id, customer_id FROM orders ORDER BY created_at DESC LIMIT 3) o ON o.customer_id = c.id runs without an error. Why does it not return each customer's three newest orders, and which order is missing for Ada?
Show answer
The subquery has no reference to any customer, so it is evaluated once and LIMIT 3 keeps the three newest orders in the whole table: orders 4, 3 and 5. The join only attaches those rows to customers. Ada's order 2 is among her three newest but is missing, and Ben's order 5 takes one of the three slots.
Exercise
Is this query valid, and why? SELECT c.id FROM customers c WHERE EXISTS (SELECT 1 FROM (SELECT customer_id FROM orders WHERE orders.customer_id = c.id) AS o)
Show answer
Yes. The derived table o refers to c, but c belongs to the enclosing query, not to a sibling in the same FROM list. References to an enclosing query level are allowed. Only references between FROM items at the same level need LATERAL.
Exercise
A colleague fetches each customer's latest order total and latest order date with two scalar subqueries in the SELECT list. Name two drawbacks of this form compared with a single lateral subquery.
Show answer
Each scalar subquery can return only one column and one row, so two values need two subqueries. Each one repeats the same filter and sort and runs its own lookup. A scalar subquery also cannot return several rows per customer, so it cannot produce a top-three list.