O'Reilly logo

Microsoft SQL Server 2012 Bible by Aaron Nelson, Jose Chinchilla, Patrick LeBlanc, Jorge Segarra, Adam Jorgensen

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Using Unions

The UNION operation is different from a join. In relational algebra terms, a union is addition, whereas a join is multiplication. Instead of extending a row horizontally as a join would, the union stacks multiple result sets into a single long table, as shown in Figure 9.9.

Figure 9.9 A union vertically appends the result of one SELECT statement to the result of another SELECT statement.

9.9

Unions come in three basic flavors: union, intersect union, and difference (or except) union.

Union [All]

The most common type of union by far is the UNION ALL query, which simply adds the individual SELECT's results.

In the following UNION query, the CustomerIDs from Customer2 and the CustomerIDs from SalesOrder2 are appended together into a single list. The first SELECT sets up the overall result, so it supplies the result set column headers. Each individual SELECT generates a result set for the UNION operation, so each SELECT's individual WHERE clause filters data for that SELECT. The final SELECT's ORDER BY then serves as the ORDER BY for the entire unioned results set. The ORDER BY must refer to the columns by either the first SELECT's column names or by the ordinal position of the column:

SELECT CustomerID, ‘Customer2 - Source' as Source
 FROM dbo.Customer2 
UNION ALL
SELECT CustomerID, ‘SalesOrder2 - Source' 
 FROM dbo.SalesOrder2 
 ORDER BY 1;

The resulting record set uses the ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required