SQL UNION ALL
UNION ALL stacks compatible result sets and keeps every row from each SELECT.
UNION ALL combines rows from one SELECT with rows
from another. Think of it as stacking two result grids with the same column
shape.
Each SELECT must return the same number of columns, and the
matching columns should have compatible types. Column names come from the
first SELECT.
select 'source one' as source_name, value_column
from first_table
union all
select 'source two' as source_name, value_column
from second_table Use UNION ALL when duplicates matter
UNION ALL doesn't remove duplicates. That makes it faster and
more literal than UNION: every row produced by either input is
kept in the combined result.
When the repeated rows are an accident rather than real activity, see why UNION ALL keeps duplicate rows.
Schema · Garden Shop Tables · customers, suppliers 2 tables
One row per customer. Some customers have no phone on file.
One row per supplier. Some suppliers have no contact email.
Build one Oregon contact list from customers and
suppliers. Return contact_type,
contact_name, and state, using
customer and supplier as the type labels. Sort by
contact type, then contact name.
Run your query to inspect the result.
Expected answer
- Columns: contact_type, contact_name, state.
- Rows: Oregon customers plus Oregon suppliers.
- UNION ALL keeps the rows from both inputs without deduplicating.
Related
Nested SELECTs, IN, EXISTS, and correlation.
Ranking, LAG/LEAD, and running totals at a glance.
Practice ranking, running totals, and top row per group.
The default RANGE frame groups tied rows; use ROWS.
Filter window results in a CTE or with QUALIFY.
The WITH clause, chained steps, and CTE vs subquery.