Today I observed very interesting little thing about SQL Server and I felt that I should share this with my readers.
I ran following two queries and found that I am getting different result-set. When I carefully observed I found that actually the result was same but order of the records returned is different.
USE AdventureWorks
GO
SELECT ContactID
FROM Person.Contact
GO
SELECT *
FROM Person.Contact
GO
This particular thing interested me. I knew that when “ORDER BY” is not used order of the table is not guaranteed but I was not able to reproduce simple example for the same. Every time when I countered example of different order without using ORDER BY it was very complex and not easy to explain.
Now let us discuss why the order is different even though ORDER BY clause is not used. It is common belief that when ORDER BY clause is not used it gives result following primary key index. However, it is not true always. The sentenced to remember is:
There is no order unless ORDER BY is used.
If ORDER BY clause is not used what is the SQL Server’s logic of returning the result-set. From example above it is clear that SQL Server for sure does not use Index always. In fact SQL Server uses index which gives fastest result. SQL Server Query optimizer is built with keeping performance in focus. Query optimizer always returns results using any method which is optimized for performance.
Let us observe following execution plan for the same example. This really helps us to understand what is going on behind the scene.
When SELECT ContactID is used, it uses non-clustered index to return the results, where as for SELECT * it uses clustered index to return the results. Even though clustered index is used to return result in second statement, results returned using non-clustered is faster and its costs of query execution is lesser than clustered index scan.
Summary of our experiment suggests that clustered index is not always faster and efficient than non-clustered index. When ORDER BY clause is not used similar query can return different result-set.
I would like to know your opinion on this subject.
Reference : Pinal Dave (http://blog.SQLAuthority.com)
Posted in Pinal Dave, SQL, SQL Authority, SQL Constraint and Keys, SQL Performance, SQL Query, SQL Scripts, SQL Server, SQL Tips and Tricks, T SQL, Technology