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
JOINis like placing two spreadsheets side-by-side and matching rows. AUNIONis like appending one spreadsheet below another to form one long list.
Before writing any UNION query, you must understand its non-negotiable rules:
SELECT in the UNION must return the same number of columns.SELECT must have compatible types (e.g., you cannot UNION a VARCHAR column with a DATE column in the same position).SELECT becomes the heading for the entire result set.UNION ALL.| 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 preferUNION ALL— it avoids the costly sort/deduplication step and returns results faster.
SELECT column1, column2, ...
FROM table_one
UNION [ALL]
SELECT column1, column2, ...
FROM table_two;
Keyword-by-keyword breakdown: