snippetsqlMinor
Optimized date compare in WHERE clause, convert or datediff=0?
Viewed 0 times
datediffconvertwhereoptimizeddatecompareclause
Problem
In my query I am comparing two dates in the
once using
and another using
Here are the execution plans
For 1st one using
For 2nd one using
The datatype of
Which one is more optimized?
WHERE clauseonce using
CONVERT:CONVERT(day,InsertedOn) = CONVERT(day,GETDATE())and another using
DATEDIFF:DATEDIFF(day,InsertedOn,GETDATE()) = 0Here are the execution plans
For 1st one using
CONVERTFor 2nd one using
DATEDIFFThe datatype of
InsertedOn is datetime.Which one is more optimized?
Solution
Instead, try
This expression is sargable which is what you want for optimum performance. Like @Mikael indicates, you would do well to design one of your indexes so that
WHERE InsertedOn>=CAST(GETDATE() AS date) AND
InsertedOn<DATEADD(day, 1, CAST(GETDATE() AS date))This expression is sargable which is what you want for optimum performance. Like @Mikael indicates, you would do well to design one of your indexes so that
InsertedOn is the first column, and that all the other columns used in the query are included in the index. If you have lots of columns in the query, using the table's clustered index is probably best. Read up on covering indexes.Code Snippets
WHERE InsertedOn>=CAST(GETDATE() AS date) AND
InsertedOn<DATEADD(day, 1, CAST(GETDATE() AS date))Context
StackExchange Database Administrators Q#128235, answer score: 7
Revisions (0)
No revisions yet.