The UNION operator in SQL is used to combine the result sets of two or more SELECT statements into a single result set. Each SELECT statement within the UNION must have the same number of columns in the result sets with similar data types. Here’s a detailed tutorial on how to use the UNION operator effectively.
SELECT column1, column2, ...
FROM table1
UNION
SELECT column1, column2, ...
FROM table2;
Assume you have two tables, employees_usa and employees_uk, both with columns first_name, last_name, and salary.
SELECT first_name, last_name, salary
FROM employees_usa
UNION
SELECT first_name, last_name, salary
FROM employees_uk;
This query combines the results from both tables and removes any duplicate rows.
2. Using UNION ALLTo include duplicates in the result set:
SELECT first_name, last_name, salary
FROM employees_usa
UNION ALL
SELECT first_name, last_name, salary
FROM employees_uk;
This query combines the results from both tables and includes all duplicate rows.