Queries with UNION

When you specify UNION in a query, SQL Server merges the result sets, applying one of the merge or concatenation operators with sorting strategies to remove any duplicate rows. Figure 35.25 shows an example similar to the OR strategy where the rows are concatenated and then sorted to remove any duplicates.

Figure 35.25 An execution plan for a UNION query.

image

If you specify UNION ALL in a query, SQL Server simply appends the result sets together. No intermediate sorting or merge step is needed to remove duplicates. Figure 35.26 shows the same query as in Figure 35.25, except that a UNION ALL is specified.

Figure 35.26 An execution ...

Get Microsoft® SQL Server 2008 R2 Unleashed now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.