Monday, April 11, 2011

The "UNION" of SQL

"The UNION operator is used to combine the result-set of two or more SELECT statements." Given to us by: http://www.w3schools.com/sql/sql_union.asp.

What this does it take the first "SELECT" statement, and tack on the second "SELECT" statement to the end of it.

SELECT SalesPersonID
FROM Sales.SalesPerson
UNION
SELECT ContactID
FROM HumanResources.Employee

Taking a look at this code snippet we take all of the "SalesPersonID" from "Sales.SalesPerson" and all of the "ContactID" from "HumanResources.Employee" and combine them together, even if there are duplicate records.

There is a "UNION ALL" that can be used in the place of just plain "UNION" that will actually give all the records as single records, giving no duplicated records.

No comments:

Post a Comment