
For an instructor lead, in-depth look at learning SQL click below.
In Structured Query Language (SQL), UNION and UNION ALL operators are used for combining rows from two or more tables. The goal of these operators is data integration from various sources. But although their operation appears similar, there are fundamental differences between them that you should be aware of while using them in your SQL queries.
The UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements. However, it will eliminate duplicate rows from the results. Each SELECT statement within the UNION operator must contain the same number of columns, have similar data types, and be in the same order.
1 2 3 4 5 |
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2 |
In the above code, the UNION operator is used between two SELECT statements joining the results from ‘table_name1’ and ‘table_name2’. Any duplicate results are automatically removed in the process.
The UNION ALL Operator
Just like UNION, the UNION ALL operator is used to combine the result-set of two or more SELECT statements. However, it does not remove duplicate rows from the result. Essentially, UNION ALL operator does the same as UNION, only it does not eliminate the duplicates.
1 2 3 4 5 |
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2 |
In the above code, the UNION ALL operator is used between two SELECT statements combining the results from ‘table_name1’ and ‘table_name2’. But unlike UNION, UNION ALL keeps all duplicate rows in the resulting table.
When to use UNION Vs UNION ALL
You should use UNION when you want to avoid duplicate values in the result set. This can be particularly useful when you’re looking to generate a list that only contains unique elements.
On the other hand, UNION ALL is faster than UNION. The time saved can be critical for larger databases or complex queries as it doesn’t have to do the additional work of identifying and eliminating duplicates.
Note
The column names in the result-set are usually determined by the column names in the first SELECT statement in the UNION/UNION ALL operator. So, always make sure to order your columns appropriately.
Wrapping Up
In conclusion, understanding UNION and UNION ALL operators is an essential part of SQL, giving you more flexibility and command over your data sets. With a clear understanding and the correct usage of these commands, you can combine, manipulate, and simplify complex data with ease.