โ 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โ024
name
โข Amit
โข Neha
๐จโ๐ผ employeesโ025
name
โข Ravi
โข Neha
๐ฅ 3. UNION Example
SELECT name FROM employees_2024
UNION
SELECT name FROM employees_2025;
โ Removes duplicates automatically
โ Result
name
โข Amit
โข Neha
โข Ravi
โก 4. UNION ALL
SELECT name FROM employees_2024
UNION ALL
SELECT name FROM employees_2025;
โ Keeps duplicates
โ Faster than UNION
โ Result
name
โข Amit
โข Neha
โข Ravi
โข 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_2024
UNION
SELECT name FROM employees_2025
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
โก Mini Challenge ๐ฅ
๐ Combine customer names from two branches and keep duplicates
๐ฅ Mini Challenge Solution ๐ฏ
๐ Since duplicates should remain โ use UNION ALL
โ Example Tables
๐ข branch_a_customers
customer_name
โข Amit
โข Neha
๐ข branch_b_customers
customer_name
โข Ravi
โข Neha
โ SQL Solution
SELECT customer_name
FROM branch_a_customers
UNION ALL
SELECT customer_name
FROM branch_b_customers;
โ Result
customer_name
โข Amit
โข Neha
โข Ravi
โข Neha
โ Duplicate Neha is preserved ๐ฏ
๐ง Why UNION ALL?
๐ UNION โ removes duplicates
๐ UNION ALL โ keeps duplicates + faster
Double Tap โค๏ธ For More