SQL UNION / UNION ALL
UNION and UNION ALL combine results from two or more SELECT queries.
Both must have the same number of columns with compatible data types.
🔹 Syntax
-- Removes duplicates
SELECT column1, column2 FROM table1
UNION
SELECT column1, column2 FROM table2;
-- Keeps duplicates
SELECT column1, column2 FROM table1
UNION ALL
SELECT column1, column2 FROM table2;🔹 Example: Merge Customers from Two Regions
-- Unique customers only
SELECT customer_name FROM customers_us
UNION
SELECT customer_name FROM customers_uk;
-- Include duplicates
SELECT customer_name FROM customers_us
UNION ALL
SELECT customer_name FROM customers_uk;🔹 Key Differences
| Feature | UNION | UNION ALL |
|---|---|---|
| Duplicates | Removed | Included |
| Performance | Slower (due to deduplication) | Faster |
| Use When | You want distinct results | You need all results |
🧠 Quick Recap
| Key Point | Explanation |
|---|---|
UNION | Combines results & removes duplicates |
UNION ALL | Combines results with duplicates |
| Column match | Same number and types of columns required |
| Use cases | Merge similar datasets (e.g., logs, users) |
🧩 Use UNION for clean merged data
🧩 Use UNION ALL for full raw results
