Sub topic 13
Lateral Subqueries for Per-Row Subselects
This chapter assumes you can write correlated subqueries, derived tables, and joins, and that you understand NULL and three-valued logic. A lateral subquery combines a derived table with a correlated subquery. This is a small topic, so the chapter stays focused on one question: how do you get several columns, or several rows, from a subquery that runs once per outer row?
The problem: a derived table cannot see its neighbours
A derived table is a subquery in the FROM clause. By default, it is evaluated on its own, as if it were a standalone query. It cannot refer to columns of other tables listed beside it in the same FROM clause.
Suppose you want each customer's largest order. This attempt fails:
SELECT c.name, o.id AS order_id, o.total
FROM customers c
JOIN (
SELECT id, total
FROM orders
WHERE customer_id = c.id -- error: c is not visible here
ORDER BY total DESC
LIMIT 1
) AS o ON TRUE;The database reports that c is unknown (or that the reference is invalid). The derived table is built before it knows anything about customers.
You could work around this with a correlated subquery in the SELECT list. That works for one column, but a SELECT-list subquery must return exactly one column and at most one row. If you need both the order id and its total, you would need two subqueries, each repeating the same search. You could also use a window function inside a derived table and filter on the rank. That works, but it computes ranks for every order before filtering.
LATERAL offers a third option.
What LATERAL does
The keyword LATERAL placed before a subquery in FROM allows that subquery to refer to tables that appear earlier in the same FROM clause. Conceptually, the database evaluates the subquery once for each row of the preceding table, and joins the rows it returns to that row.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE customer_id = c.id
ORDER BY total DESC
LIMIT 1
) AS o;Reading it step by step:
- Take one row from
customers, for example the customer with id 7. - Run the subquery with
c.idequal to 7. It finds that customer's orders, sorts them by total, and keeps the top one. - Join the returned row to customer 7.
- Repeat for the next customer.
The result has one row per customer who has at least one order, with several columns from the subquery. A customer with no orders produces an empty subquery result, and CROSS JOIN drops that customer.
This describes the logical model. The planner may choose a different physical strategy, as long as the result matches.
Keeping customers with no rows: LEFT JOIN LATERAL
A CROSS JOIN LATERAL behaves like an inner join. To keep customers whose subquery returns nothing, use LEFT JOIN LATERAL with a join condition. Because the correlation already happens inside the subquery, the condition is usually just ON TRUE.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
LEFT JOIN LATERAL (
SELECT id, total
FROM orders
WHERE customer_id = c.id
ORDER BY total DESC
LIMIT 1
) AS o ON TRUE;Customers with no orders now appear once, with NULL in order_id and total.
Top-N per group
The most common use of lateral subqueries is "top N rows per group". Change LIMIT 1 to LIMIT 3 and the query returns each customer's three largest orders.
SELECT c.name, o.id AS order_id, o.total
FROM customers c
CROSS JOIN LATERAL (
SELECT id, total
FROM orders
WHERE customer_id = c.id
ORDER BY total DESC, id
LIMIT 3
) AS o
ORDER BY c.name, o.total DESC;Two details matter here:
- The inner
ORDER BYdecides which rowsLIMITkeeps. Without it, you get an arbitrary three rows. Addingidas a tie-breaker makes the result deterministic when totals are equal. - The outer
ORDER BYcontrols the final display order. The order of rows coming out of the join is not guaranteed unless you ask for it.
Comparing the alternatives
For the same "latest or largest row per group" question you have several choices.
| Approach | Returns several columns | Returns several rows per group | Notes |
|---|---|---|---|
| Correlated subquery in SELECT list | No, one column per subquery | No, one row only | Simple, but repeats work for each column |
| Window function (`ROW_NUMBER()`) in a derived table | Yes | Yes | Ranks every row before filtering |
| `LATERAL` subquery | Yes | Yes | Reads like a loop, can use an index per group |
| Join to a `MAX()` aggregate | Yes | No | Ties return more than one row |
The lateral form often performs well when an index supports the inner query. With an index on orders (customer_id, total DESC), each execution can read just the first few index entries for that customer instead of sorting all of that customer's orders. If most customers have many orders and you only want a few, this can be much cheaper than ranking every order. If you want N rows from nearly every group and the groups are tiny, a window function can be just as fast. Check the query plan rather than assuming.
Lateral with set-returning functions
In PostgreSQL, LATERAL also lets a function in FROM use columns from earlier tables. A function call that refers to an earlier table is treated as lateral automatically, but writing the keyword makes your intent clear. For example, generate_series can produce one row per day for each booking:
SELECT b.id, d.day::date
FROM bookings b
CROSS JOIN LATERAL generate_series(b.start_date, b.end_date, interval '1 day') AS d(day);This expands each booking into one row per day of its stay. The function is specific to PostgreSQL, but the idea applies wherever the database supports lateral references.
Database support and other spellings
Support differs across systems. Check your version before relying on it.
| Database | Syntax |
|---|---|
| PostgreSQL (9.3 and later) | `CROSS JOIN LATERAL`, `LEFT JOIN LATERAL ... ON TRUE` |
| MySQL (8.0.14 and later) | `JOIN LATERAL` and `LEFT JOIN LATERAL ... ON TRUE` |
| Oracle (12c and later) | `CROSS APPLY`, `OUTER APPLY`, and `LATERAL` |
| SQL Server | `CROSS APPLY` (like inner join) and `OUTER APPLY` (like left join) |
| SQLite | Not supported |
CROSS APPLY and OUTER APPLY are the SQL Server equivalents of CROSS JOIN LATERAL and LEFT JOIN LATERAL ... ON TRUE. SQL Server uses TOP (1) in place of LIMIT 1:
SELECT c.name, o.id AS order_id, o.total
FROM customers c
OUTER APPLY (
SELECT TOP (1) id, total
FROM orders
WHERE customer_id = c.id
ORDER BY total DESC
) AS o;Common errors
- Missing
LATERAL. Referencing an earlier table in a derived table without the keyword gives an "invalid reference" error. AddLATERAL, or useAPPLYin SQL Server. - Referring to a later table. A lateral subquery sees only tables to its left in the FROM clause. Reorder the tables if you need a different table visible.
- Lost rows.
CROSS JOIN LATERALremoves outer rows whose subquery returns nothing. UseLEFT JOIN LATERAL ... ON TRUEto keep them. - Missing inner
ORDER BY.LIMITwithoutORDER BYreturns arbitrary rows, so results can change between runs. - Forgetting
ON TRUE. PostgreSQL and MySQL require anONclause withLEFT JOIN LATERAL. - Right and full joins. A lateral reference cannot be combined with
RIGHT JOINorFULL JOINwhen the lateral item is on the side that would be preserved. PostgreSQL rejects this. Rewrite it as aLEFT JOIN.
Reading the plan
In PostgreSQL, run EXPLAIN ANALYZE on the lateral query. You will typically see a Nested Loop with the outer table on one side and the subquery on the other. Look at the loops count on the inner side. It equals the number of outer rows. If each loop uses an Index Scan or Index Only Scan and is quick, the query scales well. If each loop does a Seq Scan on orders, the query reads the whole table once per customer, and you should add an index on the correlation column. The next chapter covers plan reading in more detail.
Exercise
Write a query that returns every customer together with the date and total of their most recent order, using the columns orders(id, customer_id, order_date, total). Customers with no orders must still appear. Which join type and which clause do you need, and why?
Show answer
Use a left lateral join with a subquery ordered by date descending and limited to one row: SELECT c.name, o.orderdate, o.total FROM customers c LEFT JOIN LATERAL ( SELECT orderdate, total FROM orders WHERE customerid = c.id ORDER BY orderdate DESC, id DESC LIMIT 1 ) AS o ON TRUE; LEFT JOIN keeps customers whose subquery returns no row, with NULL in the order columns. LATERAL lets the subquery use c.id, and the subquery can return two columns, which a SELECT-list subquery cannot. ON TRUE is required because the correlation is already inside the subquery. The inner ORDER BY with the id tie-breaker makes "most recent" deterministic.
Exercise
A colleague's query uses CROSS JOIN LATERAL to fetch each product's three most recent reviews. Products with no reviews are missing from the output, and the manager wants them listed. What is the smallest change that fixes this?
Show answer
Replace CROSS JOIN LATERAL with LEFT JOIN LATERAL and add ON TRUE after the subquery alias. CROSS JOIN drops outer rows when the subquery returns no rows. LEFT JOIN keeps them and fills the review columns with NULL.