UNION: combining two result sets
Every query so far has pulled rows from one place - one table, or one set of
joined tables. UNION does something different: it stacks the results of
two separate SELECT statements into a single result, one on top of the
other. The two selects need the same number of columns, in compatible types,
but they can come from entirely different tables.
UNION also removes duplicate rows automatically, the same way SELECT DISTINCT would - if the same row shows up from both sides, you only see it
once. UNION ALL is the other option: it keeps every row, duplicates
included, and is faster since it skips the dedup step. Reach for UNION when
a repeated value should only count once; reach for UNION ALL when you want
the raw combined total.
There are two tables: customers (id, email) and suppliers (id,
email) - one email, [email protected], happens to appear in both.
Your task: return one column of every distinct email address across both
customers and suppliers, with no duplicates.
You'll practice:
- Combining two
SELECT statements with UNION
- Seeing
UNION collapse a value that appears in both source tables into one row