✅ UNION & UNION ALL in SQL
🧠 1. What is UNION?
UNION is used to combine results from multiple SELECT queries
"Merge data from two tables into one result”
⚡ 2. Rules for UNION
- Same number of columns
- Same datatype/order of columns
📊 Example Tables
👨💼 employees_2025
Name
- Ajit
- Neha
👨💼 employees_2026
name
- Sujit
- Neha
🔥 3. UNION Example
SELECT name FROM employees_2025
UNION
SELECT name FROM employees_2025;
✔️ Removes duplicates automatically
✅ Result
name
- Ajit
- Neha
- Sujit
⚡ 4. UNION ALL
SELECT name FROM employees_2025
UNION ALL
SELECT name FROM employees_2026;
- Keeps duplicates
- Faster than UNION
✅ Result
name
- Ajit
- Neha
- Sujit
- Neha
🔥 5. UNION vs UNION ALL
UNION
- Removes duplicates
- Slower
- Doesn't keep all rows
UNION ALL
- Doesn't remove duplicates
- Faster
- Keeps all rows
⚡ 6. ORDER BY with UNION
SELECT name FROM employees_2025
UNION
SELECT name FROM employees_2026
ORDER BY name;
🎯 7. Practice Tasks
1. Combine employee names using UNION
2. Combine employee names using UNION ALL
3. Identify duplicate removal
4. Sort UNION result using ORDER BY
5. Compare UNION vs UNION ALL output
🧠 Why UNION ALL?
👉 UNION → removes duplicates
👉 UNION ALL → keeps duplicates + faster
#union #union_alll
No comments:
Post a Comment