Difference Between UNION and UNION ALL in SQL
Q: What is the difference between the UNION and UNION ALL operators in SQL?
- SQL Developer
- Mid level question
Explore all the latest SQL Developer interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create SQL Developer interview for FREE!
The difference between the UNION and UNION ALL operators in SQL lies in how they handle duplicate rows in the results.
The UNION operator combines the results of two or more SELECT queries and removes duplicate rows from the final output. This means that each row in the result set will be unique. For example:
```sql
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;
```
In this case, if `table1` has the value 'A' and `table2` also has 'A', the final result will only show 'A' once.
On the other hand, the UNION ALL operator also combines the results of two or more SELECT queries but includes all duplicates, meaning if the same row appears in both queries, it will be included multiple times in the final output. For instance:
```sql
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;
```
In this scenario, if both tables contain the value 'A', the result will display 'A' twice, reflecting all occurrences.
To summarize, use UNION when you want to eliminate duplicates, and use UNION ALL when you want to retain all occurrences, including duplicates.
The UNION operator combines the results of two or more SELECT queries and removes duplicate rows from the final output. This means that each row in the result set will be unique. For example:
```sql
SELECT column1 FROM table1
UNION
SELECT column1 FROM table2;
```
In this case, if `table1` has the value 'A' and `table2` also has 'A', the final result will only show 'A' once.
On the other hand, the UNION ALL operator also combines the results of two or more SELECT queries but includes all duplicates, meaning if the same row appears in both queries, it will be included multiple times in the final output. For instance:
```sql
SELECT column1 FROM table1
UNION ALL
SELECT column1 FROM table2;
```
In this scenario, if both tables contain the value 'A', the result will display 'A' twice, reflecting all occurrences.
To summarize, use UNION when you want to eliminate duplicates, and use UNION ALL when you want to retain all occurrences, including duplicates.


