Sub topic 1
The Problem: Subqueries in `FROM` Cannot See Their Neighbours
A subquery in the FROM clause is called a derived table. It produces a temporary result that the outer query can treat like a table. Without LATERAL, that subquery is independent of the other items listed in FROM.
This means a derived table cannot refer to a table alias next to it, even when that alias appears earlier in the FROM clause.
Prerequisites
This chapter assumes that you know basic SELECT, WHERE, ORDER BY, and LIMIT clauses, as well as inner joins, left joins, subqueries in FROM, and table aliases.
A derived table has its own scope
Suppose you want to find orders for each customer. You might try to put a query for the orders beside the customers table:
-- Fails: the subquery cannot refer to c
SELECT c.id, o.total
FROM customers AS c
JOIN (
SELECT total
FROM orders
WHERE orders.customer_id = c.id
) AS o ON true;PostgreSQL rejects this query because c is not visible inside the subquery. The alias c belongs to the outer query's FROM list. The subquery has its own query level, and ordinary subqueries in FROM cannot reach sideways into neighbouring FROM items.
A typical error is:
ERROR: invalid reference to FROM-clause entry for table "c"The problem is not the join condition. ON true is valid SQL. The problem occurs earlier, while PostgreSQL parses the reference to c.id inside the derived table.
Why ordinary joins are not enough
A normal join combines two row sources. Each source is normally defined independently, and the join condition decides which rows match afterward.
For example, this query works because the subquery does not depend on c:
SELECT c.id, o.total
FROM customers AS c
JOIN (
SELECT customer_id, SUM(total) AS total
FROM orders
GROUP BY customer_id
) AS o
ON o.customer_id = c.id;The subquery first calculates one total for every customer. The outer join then matches those totals to customers.
However, some tasks need the right side to depend on the current left-side row. Consider “the three newest orders for each customer.” The order query needs the current customer's ID before it can filter, sort, and limit the orders.
A single independent derived table cannot express that per-customer dependency:
-- This limits the entire orders table, not three orders per customer
SELECT c.id, o.id AS order_id
FROM customers AS c
JOIN (
SELECT id, customer_id
FROM orders
ORDER BY created_at DESC
LIMIT 3
) AS o
ON o.customer_id = c.id;This query returns only the three newest orders in the whole table. It does not return three orders for every customer. The LIMIT is applied before the join, so it has no customer-specific context.
| Query shape | What `LIMIT 3` means |
|---|---|
| Independent subquery in `FROM` | Three rows for the entire subquery |
| Per-row lateral subquery | Three rows for each current left-side row |
The missing capability
The keyword LATERAL changes the scope rules for a FROM item. It tells PostgreSQL that the item may refer to columns from FROM items written before it.
Conceptually, PostgreSQL can then process the query like this:
Take one customer
Run the order subquery using that customer's ID
Return that customer's matching rows
Take the next customer
Run the order subquery againThe subquery is still written once, but it is evaluated with a different left-side row as its input each time. This is why LATERAL is useful for top-N-per-group queries and other row-dependent lookups.
The dependency flows from left to right:
LATERAL does not make every table visible everywhere. Ordering still matters. A lateral item can reference only items that appear before it in the same FROM list. It cannot reference a table listed after it.
The next chapter shows the syntax for LATERAL and how PostgreSQL evaluates it once for each left-side row.
Exercise
Why does the following query return at most three orders overall instead of three orders per customer? SELECT c.id, o.id AS orderid FROM customers AS c JOIN ( SELECT id, customerid FROM orders ORDER BY createdat DESC LIMIT 3 ) AS o ON o.customerid = c.id;
Show answer
The subquery is evaluated independently before the join, so LIMIT 3 applies to the entire orders result. It has no access to the current customer. A lateral subquery is needed to apply the limit separately for each customer.