HiveBrain v1.2.0
Get Started
← Back to all entries
snippetsqlMinor

Optimized date compare in WHERE clause, convert or datediff=0?

Submitted by: @import:stackexchange-dba··
0
Viewed 0 times
datediffconvertwhereoptimizeddatecompareclause

Problem

In my query I am comparing two dates in the WHERE clause

once using CONVERT:

CONVERT(day,InsertedOn) = CONVERT(day,GETDATE())


and another using DATEDIFF:

DATEDIFF(day,InsertedOn,GETDATE()) = 0


Here are the execution plans

For 1st one using CONVERT

For 2nd one using DATEDIFF

The datatype of InsertedOn is datetime.

Which one is more optimized?

Solution

Instead, try

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.