The SQL UNION operator combines two or more SELECT statements.
The SQL UNION Operator
The UNION operator is used to combine the result-set of two or more SELECT statements.Notice that each SELECT statement within the UNION must have the same number of columns. The columns must also have similar data types. Also, the columns in each SELECT statement must be in the same order.
SQL UNION Syntax
SELECT column_name(s) FROM table_name1
UNION
SELECT column_name(s) FROM table_name2
UNION
SELECT column_name(s) FROM table_name2
SQL UNION ALL Syntax
SELECT column_name(s) FROM table_name1
UNION ALL
SELECT column_name(s) FROM table_name2
UNION ALL
SELECT column_name(s) FROM table_name2
SQL UNION Example
Look at the following tables:"Employees_Norway":
E_ID | E_Name |
---|---|
01 | Hansen, Ola |
02 | Svendson, Tove |
03 | Svendson, Stephen |
04 | Pettersen, Kari |
E_ID | E_Name |
---|---|
01 | Turner, Sally |
02 | Kent, Clark |
03 | Svendson, Stephen |
04 | Scott, Stephen |
We use the following SELECT statement:
SELECT E_Name FROM Employees_Norway
UNION
SELECT E_Name FROM Employees_USA
UNION
SELECT E_Name FROM Employees_USA
E_Name |
---|
Hansen, Ola |
Svendson, Tove |
Svendson, Stephen |
Pettersen, Kari |
Turner, Sally |
Kent, Clark |
Scott, Stephen |
SQL UNION ALL Example
Now we want to list all employees in Norway and USA: SELECT E_Name FROM Employees_Norway
UNION ALL
SELECT E_Name FROM Employees_USA
UNION ALL
SELECT E_Name FROM Employees_USA
E_Name |
---|
Hansen, Ola |
Svendson, Tove |
Svendson, Stephen |
Pettersen, Kari |
Turner, Sally |
Kent, Clark |
Svendson, Stephen |
Scott, Stephen |
No comments:
Post a Comment