Davide Mauri Blog

Experiences with SQL Server

Beware! SELECT TOP is BUGGED!

Yes it is true. And this bug has just been discovered by me and confirmed by the Query Optimizer Project Lead (Conor Cunningham) himself, that i have the chance to meet at SQL PASS 2005.

He has been very kind and after I exposed the problem to him, after a little bit of suprise :-), in few days he confirmed that in some circustances SET ROWCOUNT, which is deprecated, is faster than the usually better SELECT TOP.

You can test it yourself, downloading the script right here. I must say that the problem only shows when you need to limit the rows returned by your query while you're sorting over a colum with no index. At least this is my experience. Fortnately this is really an uncommon scenario so the bug is not really a tremendous one, but ouy should better know it since using SET ROWCOUNT under this cirumnstances can speed up your query by more that 3/4 times!

I've been also confirmed that this bug will not be fixed in the forthcoming version of SQL Server 2005 but will be fixed in the first service pack.

So, as we say in Itay: "Man advised man half saved" :-)

 

Legacy Comments


Alex Papadimoulis
2005-10-21
re: Beware! SELECT TOP is BUGGED!
I've heard this a few times before as well. I didn't realize it was a bug, but thought it was the way that the two worked -- ROWCOUNT happening pre-order and TOP happening post-order. Glad you cleared that up -- thankfully I've never needed that much more performance out of "TOP" ..

Adam Machanic
2005-10-22
re: Beware! SELECT TOP is BUGGED!
Just to clarify, SET ROWCOUNT is not deprecated for SELECT, but only for INSERT/UPDATE/DELETE.

This is per the SS2005 BOL, "Deprecated Features" topic.

Adam Machanic
2005-10-22
re: Beware! SELECT TOP is BUGGED!
Just to clarify, SET ROWCOUNT is not deprecated for SELECT, but only for INSERT/UPDATE/DELETE.

This is per the SS2005 BOL, "Deprecated Features" topic.

Garry
2006-05-10
re: Beware! SELECT TOP is BUGGED!
I have been fighting this same issue for days. This is the first specific posting I could find about it. I have service pack 1 installed and it still is stuffed.

I have a query which takes 1 second on sql server 2k and 3minutes on 2005.

Even the set Rowcount sucks.

Any other work arounds to get the first record?

Davide Mauri
2006-05-11
re: Beware! SELECT TOP is BUGGED!
I haven't had the time to try the query hint "FAST" yet, but maybe it can help: http://blogs.msdn.com/queryoptteam/archive/2006/03/30/564912.aspx

Davide Mauri
2006-05-11
re: Beware! SELECT TOP is BUGGED!
Gary: I forgot to say that with very small values for TOP (e.g TOP (1)), seems that the bug doesnt' affect the query