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.
select column_one, column_two
from first_table
union all
select column_one, column_two
from second_table
order by column_oneCompatibility 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.
select state
from customers
union
select state
from suppliers
order by stateINTERSECT
INTERSECT returns rows that appear in both result sets. It is useful for finding overlap, such as values shared by two groups.
select state
from customers
intersect
select state
from suppliersEXCEPT
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.
select customer_id
from customers
except
select customer_id
from orders| Operator | What it does | Duplicate behavior |
|---|---|---|
UNION ALL | Stacks all rows. | Keeps duplicates. |
UNION | Stacks rows. | Removes duplicate rows. |
INTERSECT | Keeps only shared rows. | Returns distinct shared rows. |
EXCEPT | Subtracts the second result. | Returns distinct remaining rows. |
Put one ORDER BY at the end of the full set operation. Ordering the individual inputs usually does not control the final combined order.