UNION vs UNION ALL in SQL Explained
Q: What is the difference between UNION and UNION ALL?
- SQL
- Senior level question
Explore all the latest SQL interview questions and answers
ExploreMost Recent & up-to date
100% Actual interview focused
Create SQL interview for FREE!
The primary difference between UNION and UNION ALL is that UNION will remove duplicates from the result set while UNION ALL does not.
UNION:
1. Combines the results of two or more SELECT statements into a single result set.
2. Removes any duplicate rows from the result set.
3. Takes longer to execute than UNION ALL.
UNION ALL:
1. Combines the results of two or more SELECT statements into a single result set.
2. Does not remove duplicate rows from the result set.
3. Executes faster than UNION.
Example:
Let’s say we have two tables named table_1 and table_2 with the following data:
Table_1
Name Age
John 25
Tim 30
Table_2
Name Age
Tim 30
Sam 20
If we use the UNION statement on these two tables, the result will be:
Name Age
John 25
Tim 30
Sam 20
However, if we use the UNION ALL statement on these two tables, the result will be:
Name Age
John 25
Tim 30
Tim 30
Sam 20
UNION:
1. Combines the results of two or more SELECT statements into a single result set.
2. Removes any duplicate rows from the result set.
3. Takes longer to execute than UNION ALL.
UNION ALL:
1. Combines the results of two or more SELECT statements into a single result set.
2. Does not remove duplicate rows from the result set.
3. Executes faster than UNION.
Example:
Let’s say we have two tables named table_1 and table_2 with the following data:
Table_1
Name Age
John 25
Tim 30
Table_2
Name Age
Tim 30
Sam 20
If we use the UNION statement on these two tables, the result will be:
Name Age
John 25
Tim 30
Sam 20
However, if we use the UNION ALL statement on these two tables, the result will be:
Name Age
John 25
Tim 30
Tim 30
Sam 20


