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.


About The Author

Madhivanan,an MSc computer Science graduate from Chennai-India, works as a works as a Lead Subject Matter Expert at a company that simplifies BIG data. He started his career as a developer working with Visual Basic 6.0, SQL Server 2000 and Crystal Report 8. As years went by, he started working more on writing queries in SQL Server. He now has good level of knowledge in SQLServer, Oracle, MySQL and PostgreSQL as well. He is also one of the leading posters at www.sqlteam.com and a moderator at www.sql-server-performance.com. His T-sql blog is at http://beyondrelational.com/blogs/madhivanan

No comments: