If you are a fresher learning SQL, you might get confused between UNION and UNION ALL. Don’t worry, in this blog we will explain the difference between UNION and UNION ALL in SQL with very simple examples that any beginner in India can understand.
What is UNION?
UNION
is used to combine results of two or more SELECT queries.- It shows unique rows only (removes duplicates).
Example:
SELECT name FROM Class10A
UNION
SELECT name FROM Class10B;
This will remove duplicates and show only unique student names.
What is UNION ALL?
UNION ALL
also combines results of two or more SELECT queries.- But it keeps duplicates also.
Example:
SELECT name FROM Class10A
UNION ALL
SELECT name FROM Class10B;
This will keep duplicates.
Key Difference Between UNION and UNION ALL
Feature | UNION (Unique) | UNION ALL (All Records) |
---|---|---|
Duplicates | Removed | Kept |
Performance | Slower (removes duplicates) | Faster (keeps all rows) |
Use Case | When you need unique values only | When you need all values, including duplicates |
Quick Analogy
Imagine two classrooms:
- UNION = Merge attendance lists → Duplicate names appear only once.
- UNION ALL = Merge attendance lists → Duplicate names shown multiple times.
Conclusion
- Use UNION if you want unique data only.
- Use UNION ALL if you want all data (including duplicates).
That’s the simple difference between UNION and UNION ALL in SQL.