Skip to content
Reference/SQL Set Operations
Reference

SQL Set Operations

How to stack, deduplicate, overlap, and subtract compatible SELECT results.

Set operations combine whole result sets. Instead of joining columns side by side, they stack or compare rows from separateSELECT statements.

Basic shape
select column_one, column_two
from first_table
union all
select column_one, column_two
from second_table
order by column_one

Compatibility rules

Every SELECT in a set operation must return the same number of columns. Matching columns should have compatible types, and the output column names come from the first SELECT.

UNION ALL and UNION

UNION ALL stacks rows and keeps every row. UNIONstacks rows and removes duplicate rows from the combined result. PreferUNION ALL unless deduplication is part of the question.

Distinct values from two sources
select state
from customers
union
select state
from suppliers
order by state

INTERSECT

INTERSECT returns rows that appear in both result sets. It is useful for finding overlap, such as values shared by two groups.

Shared values
select state
from customers
intersect
select state
from suppliers

EXCEPT

EXCEPT returns rows from the first result set after removing rows that appear in the second result set. It is useful for missing-list questions.

Rows in one result but not another
select customer_id
from customers
except
select customer_id
from orders
OperatorWhat it doesDuplicate behavior
UNION ALLStacks all rows.Keeps duplicates.
UNIONStacks rows.Removes duplicate rows.
INTERSECTKeeps only shared rows.Returns distinct shared rows.
EXCEPTSubtracts the second result.Returns distinct remaining rows.
Ordering

Put one ORDER BY at the end of the full set operation. Ordering the individual inputs usually does not control the final combined order.