sqlsql-serverdatediffgetdatedatecreated

can someone please explain this SQL code?


WHERE(DATEDIFF(MONTH, datecreated, GETDATE()) = +1)

What should this do?


Solution

  • This is getting everything in the previous calendar month. Note that this is specifically the previous calendar month, regardless of the current date.

    Why is this the case? datediff() counts the number of boundaries between two date/time values. In this case, the boundary is the beginning/end of a month. So, if today is 2017-05-05, then anything in 2017-04 has a single boundary. Nothing in March does, nothing in May does. Note that this is as true on May 1st as on May 31st.

    Although this is handy, I think the code should at least have a comment, because it might not be obvious to a casual reader what is happening.