📝 What You’ll Learn
- What
UNIONdoes - Syntax and structure
- Examples of using
UNION - Difference between
UNIONandUNION ALL
🔄 What Is UNION?
The UNION operator in SQL is used to combine the result sets of two or more SELECT queries into a single result set.
- It eliminates duplicate rows by default.
It’s useful when you need to combine data from similar tables or queries with the same structure.
🧱 UNION Syntax
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
🧪 Example: Combine Customers from Two Regions
SELECT name, region
FROM customers_east
UNION
SELECT name, region
FROM customers_west;
This query combines the customers from the East and West regions into a single list, excluding duplicates.
🧪 Example: Combine Products and Services
SELECT product_name AS item_name
FROM products
UNION
SELECT service_name AS item_name
FROM services;
Here, we’re combining products and services into one column, showing all unique items.
⚖️ UNION vs UNION ALL
| Feature | UNION | UNION ALL |
|---|---|---|
| Duplicates | ✅ Removes duplicates | ❌ Does not remove |
| Performance | ⏳ Slightly slower | 🚀 Faster |
| Use Case | When you need unique results | When you want all results |
📘 Recap
UNIONcombines results from multiple queries into a single result set- Removes duplicate rows by default
UNION ALLincludes all rows, even duplicates