Concept · Advanced SQL

UNION ALL

UNION ALL combines compatible results and keeps every row, including repeated ones.

Before continuing: This entry is part of the UNION guide. If you are new to the topic, start with UNION.

UNION ALL example

We gather the categories of products that are out of stock and of products priced above 200:

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

«Computers» appears twice because it meets both conditions. UNION ALL keeps that information instead of turning it into a list of unique values.

Check the result with small data

The same product is stocked in two shops.

Self-contained query · SQLite
WITH store_a(product) AS (VALUES ('Mouse'),('Display')),
     store_b(product) AS (VALUES ('Mouse'))
SELECT product FROM store_a UNION ALL
SELECT product FROM store_b;
Query result
product
Mouse
Display
Mouse

UNION ALL keeps both occurrences of Mouse. It is a good fit for consolidating records when you want to keep the repeats.

Check your understanding: How many Mouse rows would be left with UNION instead of UNION ALL?

Show answer

One: UNION would remove the repetition and leave only Mouse and Display.

What changes from case to case

The queries must line up

As with UNION, each block needs the same number of columns, with compatible types in the same position. You can add a literal column to show where each row comes from:

Structure with a source column
SELECT name, 'customers' AS source
FROM customers
UNION ALL
SELECT name, 'employees' AS source
FROM employees;

The final column names are normally taken from the first SELECT. Apply ORDER BY to the whole set, after the last block.

Why it may be the right choice

Removing duplicates takes extra work. When you need every row, or you know the blocks cannot overlap, UNION ALL expresses the intent better and usually skips that deduplication step.

Choosing it for performance alone would be a mistake if the correct result requires unique values. Decide the meaning first; then measure.

Common mix-ups with UNION ALL

Mistaking a valid repeat for an accidental duplicate

Two identical rows can represent two real events. They can also reveal that a JOIN or a block is producing more rows than expected. Check where they come from before adding DISTINCT or switching to UNION.