SQL UNION Operator
Syntax
The UNION operator in SQL is used to combine the results of two or more SELECT statements into a single result set, eliminating duplicate rows by default. To include duplicates, use UNION ALL.
-- Combine results and remove duplicatesSELECT column1, column2FROM table1UNIONSELECT column1, column2FROM table2;
-- Combine results and include duplicatesSELECT column1, column2FROM table1UNION ALLSELECT column1, column2FROM table2;Example
-- Combine employees from two departmentsSELECT name, departmentFROM department_aUNIONSELECT name, departmentFROM department_b;/* Output (removes duplicates):| name | department ||-------------|-------------|| John Doe | Sales || Jane Smith | Marketing || Alice Brown | HR |*/
-- Combine employees and include duplicatesSELECT name, departmentFROM department_aUNION ALLSELECT name, departmentFROM department_b;/* Output (includes duplicates):| name | department ||-------------|-------------|| John Doe | Sales || John Doe | Sales || Jane Smith | Marketing || Alice Brown | HR |*/