Subqueries
A subquery is a SELECT statement in parentheses inside another query. A scalar subquery returns one column and at most one row, and you can use it wherever a value is allowed. If it returns more than one row, the query fails. If it returns no rows, its value is NULL. IN (subquery) tests whether a value is in the subquery's single column. EXISTS (subquery) tests whether the subquery returns any rows. ANY is true when the comparison is true for at least one row of the subquery, and ALL is true when the comparison is true for every row.
A subquery in the FROM clause is a source of rows, like a table. A correlated subquery refers to columns of the outer query and is evaluated for each outer row.
Syntax
( select )
expression [ NOT ] IN ( select )
[ NOT ] EXISTS ( select )
expression operator { ANY | ALL } ( select )
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 orders whose amount is greater than the average amount, which a scalar subquery computes.
SELECT customer, amount FROM sales_db.sales_parquet WHERE amount > ( SELECT avg(amount) FROM sales_db.sales_parquet ) ORDER BY customer
The query returns the following results.
| customer | amount |
|---|---|
|
|
|
|
The following SQL query uses a correlated subquery to find the largest order in each region.
SELECT region, customer FROM sales_db.sales_parquet AS s WHERE amount = ( SELECT max(amount) FROM sales_db.sales_parquet WHERE region = s.region ) ORDER BY region
The query returns the following results.
| region | customer |
|---|---|
|
|
|
|
|
|
The following SQL query returns the orders in sales_parquet that also appear in orders_iceberg.
SELECT order_id, customer FROM sales_db.sales_parquet WHERE order_id IN ( SELECT order_id FROM sales_db.orders_iceberg ) ORDER BY order_id
The query returns the following results.
| order_id | customer |
|---|---|
|
|
|
|
|
|
The following SQL query returns the orders in sales_parquet that have no matching row in orders_iceberg.
SELECT order_id, customer FROM sales_db.sales_parquet AS s WHERE NOT EXISTS ( SELECT 1 FROM sales_db.orders_iceberg AS o WHERE o.order_id = s.order_id ) ORDER BY order_id
The query returns the following results.
| order_id | customer |
|---|---|
|
|
|
|
|
|
The following SQL query totals each region in a subquery in the FROM clause, and then filters the totals.
SELECT region, revenue FROM ( SELECT region, sum(amount) AS revenue FROM sales_db.sales_parquet GROUP BY region ) AS r WHERE revenue > 100 ORDER BY region
The query returns the following results.
| region | revenue |
|---|---|
|
|
|
|