Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any difference between DATE_SUB() and using arithmetic operators for datetime calculation?

After I have seen a lot of questions here using the DATE_SUB() or DATE_ADD() functions instead of the arithmetic operators + or -, I was wondering if there was any difference:

Quote from the MySQL-manual:

Date arithmetic also can be performed using INTERVAL together with the + or - operator:

date + INTERVAL expr unit
date - INTERVAL expr unit

So basically, these two statements return the same result:

SELECT DATE_ADD(NOW(), INTERVAL 7 DAY);

and

SELECT NOW() + INTERVAL 7 DAY;

Now my question:

Is there any difference between DATE_SUB() and using the - operator in MySQL? (besides readability?)

like image 686
Dan Soap Avatar asked Feb 01 '10 13:02

Dan Soap


People also ask

What does Date_sub function do?

The DATE_SUB() function subtracts a time/date interval from a date and then returns the date.

Which of the following in MySQL function returns a datetime value based on a Datevalue?

MySQL LAST_DAY() returns the last day of the corresponding month for a date or datetime value. MySQL LOCALTIME returns the value of current date and time in 'YYYY-MM-DD HH:MM:SS' format or YYYYMMDDHHMMSS.

What function finds the current time and date in MySQL?

MySQL NOW() Function The NOW() function returns the current date and time. Note: The date and time is returned as "YYYY-MM-DD HH-MM-SS" (string) or as YYYYMMDDHHMMSS. uuuuuu (numeric).


1 Answers

The MySQL documentation for DATE_ADD (http://dev.mysql.com/doc/refman/5.1/en/date-and-time-functions.html#function_date-add) explicitly states that you may do date arithmetic with the + and - operators.

Date arithmetic also can be performed using INTERVAL together with the + or - operator:

date + INTERVAL expr unit

date - INTERVAL expr unit

Given that it's endorsed by the docs, I think any difference is stylistic. I personally think the +/- is easier to read (after all, you don't use INT_ADD(...) or DOUBLE_ADD(...) to manipulate numeric values, so why dates?). Others might have their own reasons for liking DATE_ADD and DATE_SUB, and that's fine too. Just pick something and stick with it.

Jemiah

like image 185
Jemiah Avatar answered Sep 17 '22 13:09

Jemiah