SQL UNION Operator

SQL UNION Operator

The SQL UNION operator is employed to mix the result sets of two or more SELECT statements. It removes duplicate rows between the varied SELECT statements. Each SELECT statement within the UNION must have an equivalent number of fields within the result sets with similar data types.

SQL UNION ALL Example
The following SQL statement returns the cities "duplicate values also" from both the Customer and the Supplier table

SELECT City FROM Customer
UNION ALL
SELECT City FROM Supplier
ORDER BY City

As you can see in this example, the UNION has taken all City values from both the supplier table as well as the orders table and returned a combined result set. Because the UNION operator removed duplicates between the result sets, the City of n.... only appears once, even though it is found in both the supplier and orders table. If you do not wish to remove duplicates, try using the UNION ALL operator instead

2020-05-07