An interesting thing about the DATEDIFF()
function in SQL Server is that it ignores your SET DATEFIRST
value.
However, this is not a bug. Microsoft’s documentation for DATEDIFF()
clearly states the following:
Specifying SET DATEFIRST
has no effect on DATEDIFF
. DATEDIFF
always uses Sunday as the first day of the week to ensure the function operates in a deterministic way.
In case you don’t know, SET DATEFIRST
sets the first day of the week for your session. It’s a number from 1 through 7 (which corresponds to Monday through Sunday).
The initial value for SET DATEFIRST
is implicitly set by the language setting (which you can set with the SET LANGUAGE
statement). The actual value will depend on the language that is set. For example the default value for the us_english
language is 7
(Sunday), whereas the default for the British
language is 1
(Monday).
However, you can use a SET DATEFIRST
statement to override this so that you can keep using the same language while using a different day for the first day of the week.
But as mentioned, the SET DATEFIRST
value has no effect on the DATEDIFF()
function. The DATEDIFF()
function always assumes that Sunday is the first day of the week regardless of your SET DATEFIRST
value.
This can cause some interesting problems when using DATEDIFF()
if you don’t know how it works.
If you find yourself in this situation, hopefully the examples on this page can help.
Continue reading →