SQL UNION operator
The UNION operator is used to combine the result sets of two or more SELECT statements.
Note that the SELECT statement inside the UNION must have the same number of columns. Columns must also have similar data types. Also, the order of the columns in each SELECT statement must be the same.
SQL UNION syntax
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
Note: By default, the UNION operator selects different values. If duplicate values are allowed, use UNION ALL.
SQL UNION ALL syntax
SELECT column_name(s) FROM table_name1 UNION ALL SELECT column_name(s) FROM table_name2
In addition, the column names in the UNION result set are always equal to the column names in the first SELECT statement in the UNION.
The original table used in the following example:
Employees_China:
E_ID | E_Name |
---|---|
01 | Zhang, Hua |
02 | Wang, Wei |
03 | Carter, Thomas |
04 | Yang, Ming |
Employees_USA:
E_ID | E_Name |
---|---|
01 | Adams, John |
02 | Bush, George |
03 | Carter, Thomas |
04 | Gates, Bill |
Using the UNION command
example
List all different employee names in China and the US:
SELECT E_Name FROM Employees_China
UNION
SELECT E_Name FROM Employees_USA
result
E_Name |
---|
Zhang, Hua |
Wang, Wei |
Carter, Thomas |
Yang, Ming |
Adams, John |
Bush, George |
Gates, Bill |
Note: This command cannot list all employees in China and the United States. In the above example, we have two employees with the same name and only one of them is listed. The UNION command just picks up distinct values.
UNION ALL
The UNION ALL command and the UNION command are almost equivalent, except that the UNION ALL command lists all values.
SQL Statement 1 UNION ALL SQL Statement 2
Using the UNION ALL command
Example:
List all employees in China and the US:
SELECT E_Name FROM Employees_China
UNION ALL
SELECT E_Name FROM Employees_USA
result
E_Name |
---|
Zhang, Hua |
Wang, Wei |
Carter, Thomas |
Yang, Ming |
Adams, John |
Bush, George |
Carter, Thomas |
Gates, Bill |