LATERAL joins
A lateral subquery in the FROM clause can refer to columns of the sources that come before it, and it is evaluated for each of their rows. Mark the subquery with LATERAL. DuckDB also treats a subquery in FROM as lateral when it refers to an earlier source without the keyword.
Use a lateral join to compute values from each row. You can also use it to return the top rows of another table for each row, such as the two largest orders in each region.
Syntax
from_item, LATERAL ( select ) [ AS ] alias
from_item CROSS JOIN LATERAL ( select ) [ AS ] alias
from_item [ INNER | LEFT
[ OUTER ] ] JOIN LATERAL ( select )
[ AS ] alias ON condition
Examples
For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.
The following SQL query returns the two largest orders in each of two regions. The lateral subquery refers to r.region from the source before it.
SELECT r.region, top_orders.customer, top_orders.amount FROM (VALUES ('east'), ('west')) AS r(region), LATERAL ( SELECT customer, amount FROM sales_db.sales_parquet AS s WHERE s.region = r.region ORDER BY amount DESC NULLS LAST LIMIT 2 ) AS top_orders ORDER BY r.region, top_orders.amount DESC
The query returns the following results.
| region | customer | amount |
|---|---|---|
|
|
|
|
|
|
|
|
|
|
|
|
The following SQL query squares each number in a subquery that refers to t.n. The subquery is lateral even though it does not use the LATERAL keyword.
SELECT t.n, sq.square FROM generate_series(1, 3) AS t(n), ( SELECT t.n * t.n AS square ) AS sq ORDER BY t.n
The query returns the following results.
| n | square |
|---|---|
|
|
|
|
|
|