SQL Server: Behavioral Change in Union Operator

There is a behavioral change in the SQL Server UNION operator from version starting from 2005.

In versions prior to SQL Server 2005, the union operator would not only remove duplicates but also order the resultset by the first column.

For eg: run this code in SQL Server version 2000

select 2 as number
union
select 1


and observe the results. The result set is ordered by number in an ascending order

sql-2000-union

But the same code will not order the result set in version 2005. Run the same code  and see the result set


sql-2005-union

Now run same query in SQL 2008, and observe the results! Also note that when there is a duplicate, union will behave the same way in all versions.

No comments:

Post a Comment