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 πΉ Example: Merge Customers from Two Regions πΉ Key Differences Feature UNION UNION ALL Duplicates Removed Included Performance Slower (due to deduplication) Faster Use When You want distinct results You […]
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
Was this helpful?
Thanks for your feedback!