DB2 UNION vs. UNION ALL Explained | Generated by AI

Home 2026.01

Question: What do UNION ALL and UNION mean in DB2?

Answer:

In DB2 (and in SQL in general), both UNION and UNION ALL are set operators used to combine the result sets of two or more SELECT statements into a single result set. They stack rows vertically (append rows from one query below the rows of another).

Key Differences

Comparison Table

Feature UNION UNION ALL
Removes duplicates? Yes No
Performance Slower (needs to sort/dedup) Faster (no deduplication)
Use when… You want distinct rows only You want all rows (even duplicates)
Typical use case Combining similar data without repetition Aggregating logs, history + current data, recursive CTEs

Rules that apply to both

Simple Example

-- Assume these two tables have some overlapping CITY values

SELECT CITY FROM CUSTOMERS
UNION
SELECT CITY FROM SUPPLIERS;
-- Returns only unique cities

SELECT CITY FROM CUSTOMERS
UNION ALL
SELECT CITY FROM SUPPLIERS;
-- Returns all cities, including duplicates if the same city appears in both tables

Performance Note

UNION ALL is almost always faster than UNION because DB2 does not have to compare rows for duplicates (which usually involves sorting or hashing).
Use UNION ALL by default unless you explicitly need to remove duplicates.

Special Case

In recursive Common Table Expressions (CTE) in DB2, you must use UNION ALL between the anchor and recursive members — UNION is not allowed.

References:


Back

x-ai/grok-4.1-fast

Donate