What Is the UNION Operator?

The UNION operator in MySQL is used to combine the result sets of two or more SELECT statements into a single result set. Rather than joining tables horizontally (side by side, as a JOIN does), UNION stacks result sets vertically — one on top of the other.

Think of it like this: imagine you have two printed reports from different departments — one for store rentals in January, another for store rentals in February. UNION is like physically stacking both reports into one pile and reading through them together as a single document.

💡 Analogy: A JOIN is like placing two spreadsheets side-by-side and matching rows. A UNION is like appending one spreadsheet below another to form one long list.


Core Rules of UNION

Before writing any UNION query, you must understand its non-negotiable rules:


UNION vs UNION ALL — The Key Difference

Feature UNION UNION ALL
Removes duplicates? ✅ Yes (automatically) ❌ No (keeps all rows)
Performance Slower (requires deduplication step) Faster (no deduplication)
Use when You need unique rows only You need all rows including duplicates

💡 When to use UNION ALL: If you are certain your data sets have no overlapping rows, always prefer UNION ALL — it avoids the costly sort/deduplication step and returns results faster.


Syntax — Fully Explained

SELECT column1, column2, ...
FROM table_one
UNION [ALL]
SELECT column1, column2, ...
FROM table_two;

Keyword-by-keyword breakdown: