SQL - Union All Operator
Here's an example to demonstrate the usage of the UNION ALL 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, you can use the UNION ALL operator as follows:
SELECT ID, Name, Department
FROM Employees
UNION ALL
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, including all rows from both tables. Here's the expected output:
ID |
Name |
Department |
1 |
John |
HR |
2 |
Jane |
Sales |
3 |
Mike |
IT |
1 |
Lisa |
New York |
2 |
Tom |
London |
3 |
Sarah |
Paris |
As you can see, the result set includes all rows from the "Employees" table and all rows from the "Customers" table, without removing any duplicates. The column names, data types, and order must match in both SELECT statements for the UNION ALL operation to work correctly.
Remember that the UNION ALL operator does not eliminate duplicate rows, which can be useful when you want to include all rows from multiple tables or queries, even if there are duplicates.