CSE Roadmap

Common tier · about 3 hours · 5 parts

Part 2 of 5 · 1 min read

UNION and UNION ALL

Combining two result sets, with or without removing duplicates.

Think of merging two mailing lists into one combined list. One approach checks for repeated names and keeps only one copy of each. The other approach just stacks both lists together, repeats included.

In plain words: UNION combines the rows of two queries, removing any duplicate rows from the combined result. UNION ALL does the same thing but keeps every duplicate. Both queries must return the same number of columns, in compatible types, in the same order.

A worked example. Every customer who placed an order in January, combined with every customer who placed one in February, counted once each even if they ordered in both months.

The key lines.

SELECT customer_id FROM orders WHERE placed_on BETWEEN '2026-01-01' AND '2026-01-31'
UNION
SELECT customer_id FROM orders WHERE placed_on BETWEEN '2026-02-01' AND '2026-02-28';

UNION, UNION ALL

UNION combines two result sets and removes duplicate rows. UNION ALL combines two result sets and keeps every row, including duplicates.

Example: a customer who ordered in both January and February appears once under UNION, twice under UNION ALL.