Search code examples
sql-servert-sqlsede

datediff and dateadd anomaly


What is the difference between the following two logic conditions (both CreationDate values are DateTime)?

   and abs(datediff(hour, a.CreationDate, e.CreationDate)) < 12

and:

   and e.CreationDate > dateadd(hour, -12, a.CreationDate)
   and e.CreationDate < dateadd(hour,  12, a.CreationDate)

(yes, there is a difference - the change produces different results, but I can't see what)

Background

A recent question came up on Meta.se about "curator" badges, and the 12-hour edit windows. That question inspired me to make a copy of an SQL query I had previously written, and to make the new copy "variable" sized edit windows, instead of just 12 hours each side. In essence, I changed the following code:

   and abs(datediff(hour, a.CreationDate, e.CreationDate)) < 12

to be:

   and e.CreationDate > dateadd(hour, -12, a.CreationDate)
   and e.CreationDate < dateadd(hour,  12, a.CreationDate)

(except the 12 values in the second statement are variables).

These two queries are in Stack Exchange Data Explorer: original and copied

The queries produce slightly different results, though... and I am really scratching my head as to why. I also cannot decide which query result is correct. I believe it must come down to something in the datediff logic... does it 'round' hours up or something, so that it has slightly fewer results?

DateDiff:

enter image description here

DateAdd:

enter image description here


Solution

  • DateDiff counts boundary crossings while DateAdd does straightforward arithmetic.

    For example, the first query would count 12 boundaries between 00:59 and 12:01, and would thus exclude that difference, but the second query would count it as being within 12 hours. This makes the second query 'right', and the first one 'wrong'.