Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL max row of a table

Tags:

sql

sql-server

Which one is better in SQL Server 2008 or it doesn't matter as the database optimizes.

SELECT * FROM table
WHERE datecolumn = (SELECT max(datecolumn) FROM table);


SELECT TOP 1 * FROM table ORDER BY datecolumn DESC;
like image 760
Yada Avatar asked Dec 11 '10 16:12

Yada


1 Answers

Looking at the actual SQL execution plan for these queries, it results in exactly the same execution plan and the same execution cost. However it might differ depending on the index setup and collected statistics, therefore it is best to do the check yourself.

One thing to be aware of is that the two queries might not return the same result. The 2nd SQL will always return one record where the first record might return multiple rows if datecolumn is not unique.

like image 181
Philip Fourie Avatar answered Sep 29 '22 15:09

Philip Fourie