What's the performance difference between using Year() and using dateAdd to calculate Year in SQL Server?

StackOverflow https://stackoverflow.com/questions/23682412

  •  23-07-2023
  •  | 
  •  

Question

Just a general question for those more knowlegable than me regarding the usage and resources being used.

Is there any advantage/disadvantage between these two?

WHERE YEAR(AppointDate) = YEAR(GETDATE())

and

WHERE AppointDate BETWEEN dateadd(yy, datediff(yy, 0, GETDATE()), 0) AND GETDATE()

Basically gettting a list YTD of column

Was it helpful?

Solution

Although logically the two might produce the same results, their efficiency is quite different.

The first where clause applies the YEAR() function to the AppointDate column of every row, which is costly and therefore inefficient. It also means that any indexes built on the column could not be used.

The second where clause generates constant values once at the start of the query and compares them to raw values in the table, so indexes will be able to be used, and even if they aren't available is still much more efficient because it avoids any function calls over the data in the table.

Note though that if a virtual column is defined as YEAR(AppointDate) and an index built over it, the inefficiency of the first where can be avoided, but it takes special treatment and permanent table alteration to achieve.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top