The UNION operator combines the result sets of two or more SELECT statements into a single result. By default, UNION removes duplicate rows from the combined output. To keep all rows including duplicates, use UNION ALL.
Every SELECT in a UNION must follow two rules:
SELECT must return the same number of columns.The column names in the final result come from the first SELECT statement.
SELECT column1, column2 FROM table_a
UNION
SELECT column1, column2 FROM table_b;
Suppose you have two tables — one for current customers and one for archived customers — and you want a single list of all unique cities:
SELECT city FROM customers
UNION
SELECT city FROM archived_customers
ORDER BY city;
| city |
|---|
| Chittagong |
| Dhaka |
| Rajshahi |
| Sylhet |
Even if "Dhaka" appears in both tables, it only appears once in the result because UNION removes duplicates.
ORDER BY clause goes at the very end — after all the SELECT statements — and applies to the entire combined result.
UNION ALL skips the duplicate-removal step, which makes it faster. Use it when you know there are no duplicates or when you intentionally want to count all occurrences:
SELECT city FROM customers
UNION ALL
SELECT city FROM archived_customers
ORDER BY city;
| city |
|---|
| Chittagong |
| Dhaka |
| Dhaka |
| Rajshahi |
| Sylhet |
"Dhaka" now appears twice — once from each table.
UNION ALL when you know duplicates cannot exist or do not matter. UNION must sort and compare all rows to eliminate duplicates, which adds overhead on large result sets.
You can combine full rows, not just single columns. This example merges active orders with a historical orders table into one report:
SELECT id, customer_id, amount, 'active' AS status
FROM orders
UNION ALL
SELECT id, customer_id, amount, 'archived' AS status
FROM orders_archive
ORDER BY id;
A literal string 'active' or 'archived' is used as a tag column so you can tell which table each row came from.
UNION removes duplicate rows; UNION ALL keeps them all.SELECT statements in a union must return the same number of columns with compatible types.SELECT.ORDER BY at the end sorts the entire combined result.UNION ALL for better performance when duplicates are not a concern.SELECT statement nested inside another query to filter or compute values dynamically.