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 31.24 shows an example similar to the OR strategy where the rows are concatenated and then sorted to remove any duplicates.

Image

FIGURE 31.24 An execution plan for a UNION query.

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 31.25 shows the same query as in Figure 31.24, except that a UNION ALL is specified.

FIGURE 31.25 An execution ...

Get Microsoft® SQL Server 2012 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.