SQL UNION operator
UNION operation result set operator for combining two or more of the SELECT statement.
Please note that the interior of the UNION SELECT statement must have the same number of columns. The columns must also have similar data types. Meanwhile, the order of columns in each SELECT statement must be the same. PURPOSE check out the data type of consent
SQL UNION Syntax
SELECT column_name(s) FROM table_name1 UNION SELECT column_name(s) FROM table_name2
Note: By default, UNION operator to select a different value. If you allow duplicate values, 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, UNION result set is always equal to the column names in the first column name UNION SELECT statement.
Below the original table used in the examples:
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 |
Use UNION command
Examples
List all the different names of employees in China and the United States:
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 does not list all employees in China and the United States. In the above example, we have two employees with the same name, only one of them was listed. UNION command selects only distinct values.
UNION ALL
UNION UNION ALL command and the command is almost equivalent, but UNION ALL command lists all values.
SQL Statement 1 UNION ALL SQL Statement 2
Use UNION ALL command
Example:
List all employees in China and the United States:
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 |