Simple explanation and Example

suggest change

In simple terms:

One mistake many people make is to use a UNION when they do not need to have the duplicates removed. The additional performance cost against large result sets can be very significant.

When you might need UNION

Suppose you need to filter a table against 2 different attributes, and you have created separate non-clustered indexes for each column. @Param1 and @Param2 are SQL Server variables. The optimizer may use a different index for each branch, while UNION still removes duplicates.

SELECT C1, C2, C3 FROM Table1 WHERE C1 = @Param1
UNION
SELECT C1, C2, C3 FROM Table1 WHERE C2 = @Param2

This simplifies your performance tuning since only simple indexes are needed to perform these queries optimally. You may even be able to get by with quite a bit fewer non-clustered indexes improving overall write performance against the source table as well.

When you might need UNION ALL

Suppose you still need to filter a table against 2 attributes, but you do not need to filter duplicate records (either because it doesn’t matter or your data wouldn’t produce any duplicates during the union due to your data model design).

SELECT C1 FROM Table1
UNION ALL
SELECT C1 FROM Table2

This is especially useful when creating views that combine data designed to be physically partitioned across multiple tables (for performance, while you still want to roll the records up). Since the data is already split, having the database engine remove duplicates adds no value and just adds processing time.

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents