Just got a small question. When trying to get a single max-Value of a table. Which one is better?
SELECT MAX(id) FROM myTable WHERE (whatever)
Though I suspect the TOP 1 sort operator is over costed in the plan. I tried with TOP 1, TOP 100, >and TOP 101 and all gave me the same estimated subtree cost despite the fact that the last one >would need to sort all the rows. – Martin Smith Jul 2 at 6:53
Whether you need 1 row or 100 rows the optimizer has to do same amount of work in this example i.e. read all the rows from the table(clustered index scan).Then sort all those rows(sort opertaion) as there is no index on the column C..Finally just display which one are needed.
SELECT TOP (1) b FROM dbo.x ORDER BY b DESC
option(recompile);
SELECT TOP (100) b FROM dbo.x ORDER BY b DESC
option(recompile);
Try above code and here top 1 and top 100 shows diff cost because there is an index on column b. Thus in this case you do not need to read all rows and sort them but the work is to go to last page pointer.For one row read the last row on last leaf page of index. TFor 100 row find the last row on last page and then start the backward scan till you get the 100 rows.