Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 736
rolfl Avatar asked May 09 '15 19:05

rolfl


People also ask

What is the difference between datediff and 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.

Can datediff be used in a where clause?

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.

What is datediff?

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.

How do I find the difference between two years in SQL?

The DATEDIFF() function returns the difference between two dates.


1 Answers

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'.

like image 108
HABO Avatar answered Oct 09 '22 17:10

HABO