Set operations: UNION, INTERSECT, and EXCEPT
UNION returns the rows of both queries, INTERSECT the rows that are in both, and EXCEPT the rows of the first query that are not in the second. Without ALL, each operation removes duplicate rows from its result. With ALL, it keeps duplicates. UNION ALL keeps every row. INTERSECT ALL keeps a row as many times as it appears in the input that has fewer copies of it. EXCEPT ALL removes one copy of a row for each copy in the second query.
By default, set operations match the columns of the two queries by position, so the queries must return the same number of columns. UNION BY NAME and UNION ALL BY NAME match the columns by name instead. The result has every column name from either query, and a column that one query does not have is NULL in its rows.
An ORDER BY or LIMIT clause after the last query applies to the combined result.
Syntax
select UNION [ ALL ] [ BY NAME ] select
select INTERSECT [ ALL ] select
select EXCEPT [ 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 combines the customers of orders_iceberg with a list of two customers and removes the duplicate.
SELECT customer FROM sales_db.orders_iceberg UNION SELECT customer FROM (VALUES ('alice'), ('zoe') ) AS t(customer) ORDER BY customer
The query returns the following results.
| customer |
|---|
|
|
|
|
The following SQL query uses UNION ALL, so alice appears twice.
SELECT customer FROM sales_db.orders_iceberg UNION ALL SELECT customer FROM (VALUES ('alice'), ('zoe') ) AS t(customer) ORDER BY customer
The query returns the following results.
| customer |
|---|
|
|
|
|
|
The following SQL query matches columns by name. The second query has no customer column and the first has no region column, so those values are NULL.
SELECT order_id, customer FROM sales_db.orders_iceberg WHERE order_id = 1 UNION ALL BY NAME SELECT 'north' AS region, 7 AS order_id ORDER BY order_id
The query returns the following results.
| order_id | customer | region |
|---|---|---|
|
|
|
|
|
|
The following SQL query returns the order IDs that are in both tables.
SELECT order_id FROM sales_db.sales_parquet INTERSECT SELECT order_id FROM sales_db.orders_iceberg ORDER BY order_id
The query returns the following results.
| order_id |
|---|
|
|
|
The following SQL query returns the order IDs in sales_parquet that are not in orders_iceberg.
SELECT order_id FROM sales_db.sales_parquet EXCEPT SELECT order_id FROM sales_db.orders_iceberg ORDER BY order_id
The query returns the following results.
| order_id |
|---|
|
|
|
The following SQL query uses EXCEPT ALL, which removes only one of the two copies of the value 2.
SELECT x FROM (VALUES (1), (2), (2), (3)) AS a(x) EXCEPT ALL SELECT x FROM (VALUES (2)) AS b(x) ORDER BY x
The query returns the following results.
| x |
|---|
|
|
|