SQL - Union Operator
In SQL Server, the UNION operator is used to combine the result sets of two or more SELECT statements into a single result set. The UNION operator removes duplicate rows from the final result set by default.
The basic syntax for using the UNION operator in SQL Server is as follows:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
In this syntax, column1, column2, etc., represent the columns you want to select from the respective tables (table1, table2, etc.). The SELECT statements can include WHERE, ORDER BY, and other clauses as needed.
The UNION operator combines the result sets of the two SELECT statements and returns a single result set with the combined rows. The columns in the SELECT statements must have the same data types and be in the same order.
By default, the UNION operator removes duplicate rows from the final result set.
Here's an example to demonstrate the usage of the UNION operator in SQL Server:
Consider two tables, "Employees" and "Customers", with the following structures:
Table: Employees
ID |
Name |
Department |
1 |
John |
HR |
2 |
Jane |
Sales |
3 |
Mike |
IT |
Table: Customers
ID |
Name |
Location |
1 |
Lisa |
New York |
2 |
Tom |
London |
3 |
Sarah |
Paris |
To combine the result sets of both tables while eliminating duplicates, you can use the UNION operator as follows:
SELECT ID, Name, Department
FROM Employees
UNION
SELECT ID, Name, Location
FROM Customers;
The above query will merge the result sets of the two SELECT statements and return a single result set, eliminating any duplicate rows. Here's the expected output:
ID |
Name |
Department |
1 |
John |
HR |
2 |
Jane |
Sales |
3 |
Mike |
IT |
4 |
Tom |
london |
5 |
Sarah |
Paris |
As you can see, the result set includes all distinct rows from both tables, combining the rows from the "Employees" table and the "Customers" table. The UNION operator removes any duplicate rows from the final result set.
It's important to note that for the UNION operator to work correctly, the column names, data types, and order must match in both SELECT statements.
In summary, the UNION operator is used to combine and eliminate duplicate rows from the result sets of multiple SELECT statements.