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)
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:
DateAdd:
The DateAdd function adds a number of units to a date/time value. The result is a new date/time value. You can also subtract a number of units from a date/time value by specifying a negative value. The DateDiff function returns the difference between two date/time values.
The DATEDIFF function can also be used in a WHERE clause as well as ORDER BY and HAVING clauses. The units of time available for the DATEDIFF are the same as those for the DATEADD function.
You can use the DateDiff function to determine how many specified time intervals exist between two dates. For example, you might use DateDiff to calculate the number of days between two dates, or the number of weeks between today and the end of the year.
The DATEDIFF() function returns the difference between two dates.
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'.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With