In SQL, one of the common tasks is to combine results from multiple SELECT statements. This can be achieved using UNION or UNION ALL operators. These operators are used for merging the output of two or more SELECT queries into a single result set which includes all the rows belonging to all the queries in the union.
The UNION
and UNION ALL
operators in SQL serve slightly different purposes:
The UNION
operator selects only distinct values by comparing the results of two SELECT statements and removing duplicate rows. The two SELECT statements that form the UNION must have the same structure. They must have the same number of columns, and corresponding columns must have compatible data types.
The UNION ALL
operator, on the other hand, does not remove duplicates. It just combines the results of two or more SELECT statements.
Here is a simple example of how to use UNION
and UNION ALL
:
SELECT column_name(s) FROM table1
UNION
SELECT column_name(s) FROM table2;
SELECT column_name(s) FROM table1
UNION ALL
SELECT column_name(s) FROM table2;
In both the above examples, column_name(s) should be the same in both the queries and they should be in the same order.
When fetching data with SQL, best practices suggest using UNION
operator to avoid duplicate rows. Use UNION ALL
only if you are sure that there will be no duplicate data between your SELECT statements or if you want to include duplicate rows in your results.