Level Extreme platform
Subscription
Corporate profile
Products & Services
Support
Legal
Français
Select Max -vs- Select Top
Message
General information
Forum:
Microsoft SQL Server
Category:
SQL syntax
Miscellaneous
Thread ID:
00502179
Message ID:
00502281
Views:
20
This message has been marked as a message which has helped to the initial question of the thread.
This is a really good question. I executed the following two queries in the Northwind database on SQL Server 2000:

select *
from orders
where orderdate = (
select max(orderdate) from orders)

select *
from orders
where orderdate = (
select top 1 orderdate from orders order by orderdate desc)


The first query executed with a subtree cost of 0.00741. The second query had a subtree cost of 0.0190. Based on this, the first query is faster.

The first query produced the following query plan:
  |--Top(1)
       |--Bookmark Lookup(BOOKMARK:([Bmk1003]), OBJECT:([Northwind].[dbo].[Orders]))
            |--Index Seek(OBJECT:([Northwind].[dbo].[Orders].[OrderDate]), SEEK:([Orders].[OrderDate] IsNotNull) ORDERED BACKWARD)
The second query produced this plan:
 |--Bookmark Lookup(BOOKMARK:([Bmk1000]), OBJECT:([Northwind].[dbo].[Orders]))
       |--Nested Loops(Inner Join, OUTER REFERENCES:([Orders].[OrderDate]))
            |--Top(1)
            |    |--Index Scan(OBJECT:([Northwind].[dbo].[Orders].[OrderDate]), ORDERED BACKWARD)
            |--Index Seek(OBJECT:([Northwind].[dbo].[Orders].[OrderDate]), SEEK:([Orders].[OrderDate]=[Orders].[OrderDate]) ORDERED FORWARD)
So it looks like the optimizer has been trained to look for the first query and provided better performance. I'd stick with the first form.

-Mike
Michael Levy
MCSD, MCDBA
ma_levy@hotmail.com
Previous
Next
Reply
Map
View

Click here to load this message in the networking platform