The UNION
operator in SQL allows you to combine the result sets of two or more SELECT statements into a single result set. The UNION
operator removes duplicates from the final result set.
Syntax:
1 2 3 4 5 6 |
SELECT [column1, column2, ...] FROM table1 UNION SELECT [column1, column2, ...] FROM table2; |
Example:
1 2 3 4 5 6 7 8 |
SELECT model, color FROM cars WHERE manufacturer = 'Toyota' UNION SELECT model, color FROM cars WHERE manufacturer = 'Honda'; |
In this example, the result set will include all the rows from the cars table where the manufacturer is either Toyota
or Honda
, and the duplicates will be removed.
Note: The number of columns, data types, and column names must be the same in all the SELECT statements being combined using the UNION
operator.