Concept · Advanced SQL

UNION

UNION combines compatible results and keeps a single copy of each repeated row.

UNION example

We want a single list of the categories that have out-of-stock products or products priced above 200:

SQL
SELECT category AS label
FROM products
WHERE stock = 0
UNION
SELECT category AS label
FROM products
WHERE price > 200
ORDER BY label;

«Computers» meets both conditions but appears only once. That removal of duplicates is the main difference from UNION ALL.

Check the result with small data

Amy appears in both lists.

Self-contained query · SQLite
WITH customers(name) AS (VALUES ('Amy'),('Liam')),
     suppliers(name) AS (VALUES ('Amy'),('Eva'))
SELECT name FROM customers UNION
SELECT name FROM suppliers ORDER BY name;
Query result
name
Amy
Eva
Liam

UNION combines both lists without duplicates. To keep both appearances of Amy, you would use UNION ALL.

Check your understanding: How many rows would UNION ALL return?

Show answer

4 rows: Amy, Liam, Amy and Eva. UNION ALL keeps Amy's repeated appearance.

What changes from case to case

Three requirements before combining

  1. Each SELECT must return the same number of columns.
  2. Columns in the same position must have compatible types.
  3. Each position must mean the same thing: name with name, date with date, amount with amount.
Structure
SELECT column_1, column_2
FROM first_source
UNION
SELECT column_1, column_2
FROM second_source;

The column names in the result usually come from the first SELECT. If you need to sort, put a single ORDER BY at the end of the whole statement.

UNION or UNION ALL

Usa UNION when a repeated row adds no new information and you need a set of unique rows. Use UNION ALL when you want to keep every occurrence or you already know the blocks do not overlap. Skipping the deduplication can save work.

Common mix-ups with UNION

Combining compatible columns that mean different things

An identifier and a quantity both being numbers does not mean they belong in the same column. First define what each position in the result represents, and use clear aliases.

UNION removes duplicates between the two queries

UNION stacks the results of two queries into one. Both must return the same number of columns with compatible types, and the column names come from the first query. It is the operator for combining lists of the same shape, such as website contacts and shop contacts.

Unlike UNION ALL, removes repeated rows, comparing whole rows to do so. That deduplication costs a sort or a hash, so use UNION ALL when you know there is no overlap or you want to keep every occurrence.

Test with a value present in both sources: it should appear once. If two rows look alike but differ by a space or a capital letter, UNION treats them as different, so normalise the data before stacking. To know where each row came from, include a fixed column with its source in each query.

Self-contained case to check in SQLite

Amy is in both channels; Liam and Eva are in only one each.

Data and query · SQLite
WITH web(email) AS (
  VALUES ('amy@example.test'), ('liam@example.test')
), store(email) AS (
  VALUES ('amy@example.test'), ('eve@example.test')
)
SELECT email FROM web
UNION
SELECT email FROM store
ORDER BY email;
Verified result of the self-contained case
email
amy@example.test
eve@example.test
liam@example.test

Amy's address exists in both sources and is shown once. With UNION ALL it would appear twice.

Check your interpretation: How many rows would the query with UNION ALL return?

Show answer

4: amy@example.test would appear twice, once for each source, as well as Liam's and Eva's addresses.

Technical questions: PostgreSQL: combining queries (UNION, INTERSECT, EXCEPT) (opens in a new tab).