The SQL 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 combined result set, by default.
Here's the basic syntax:
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Some key points about the UNION
operator:
Columns in the SELECT statements must match: The number of columns and their data types in the SELECT
statements must be the same.
Columns are named from the first SELECT statement: The column names in the result set are determined by the column names specified in the first SELECT
statement.
Duplicate rows are eliminated by default: If you want to include duplicate rows, you can use the UNION ALL
operator instead of UNION
.
Column order matters: The columns must be in the same order in all SELECT
statements.
Here's an example:
SELECT employee_id, first_name, last_name
FROM employees
WHERE department = 'Sales'
UNION
SELECT employee_id, first_name, last_name
FROM employees
WHERE department = 'Marketing';
This query combines the results of two SELECT
statements, one selecting employees from the Sales department and the other selecting employees from the Marketing department, into a single result set.