Did you find this useful?
Socialize it today.


SQL UNION Operator

Tuesday, December 06, 2011

tags SQL

The SQL UNION operator is used to combine the results of two or more SELECT queries. Each SELECT statement within the UNION must have the same number of columns and similar data types.

SA Employees Table

employeeIDemployeeName
1000John Smith
1001Fred White
1002Jane Scott
1003Samuel Williams


NA Employees Table

employeeIDemployeeName
2000Maria Garcia
2001Jane Reed
2002Jack Williams
2003Fran Orman

In this example, we have two different tables that contain employee data. We can use the SQL Union Operator to combine the results from two select queries.


Syntax

SELECT tableName1.columnName1, tableName1.columnName2, etc...
FROM tableName1
UNION
SELECT tableName2.columnName1, tableName2.columnName2, etc...
FROM tableName2


Example

List the employee data for SA and NA employees.

SELECT Employees_SA.employeeID, Employees_SA.employeeName
FROM Employees_SA
UNION
SELECT Employees_NA.employeeID, Employees_NA.employeeName
FROM Employees_NA


Results

employeeIDemployeeName
1000John Smith
1001Fred White
1002Jane Scott
1003Samuel Williams
2000Maria Garcia
2001Jane Reed
2002Jack Williams
2003Fran Orman


The UNION operator combines the results from both queries.

Please help us spread the word by socializing it today!

email contact us

Did you find something wrong with the information on this page? Please take a moment to report it to us so that we can continue to improve the quality of the information on this site. Click here to report an issue with this page.



Recommended Books & Training Resources

SQL Cookbook Head First SQL: Your Brain on SQL A Learners Guide