When using MySQL, we have the option of using the ADDDATE()
and DATE_ADD()
functions whenever we want to add a specific time interval to a given date. Both these functions do the same thing, but there is one difference between them.
This article demonstrates the difference between ADDDATE()
and DATE_ADD()
in MySQL.
Syntax
The difference between these two functions is in their syntax. One function allows for two different forms, whereas the other allows for just one form.
DATE_ADD()
The DATE_ADD()
syntax goes like this.
DATE_ADD(date,INTERVAL expr unit)
This accepts a date value, followed by the INTERVAL
keyword and the expression and unit for which to add to the date supplied by the first argument.
ADDDATE()
The ADDDATE()
syntax allows for two forms. You can use either of the following forms.
ADDDATE(date,INTERVAL expr unit)
Or
ADDDATE(expr,days)
The first form is exactly the same as the DATE_ADD()
syntax. In fact, when using this syntax, the ADDDATE()
function is a synonym for DATE_ADD()
.
However, it’s the second form of the syntax that sets the two functions apart. This second form is only available when using the ADDDATE()
function, and it allows you to use a shorthand way to specify the number of days to add to the date.
Example
Here’s an example to demonstrate the difference between the two forms.
SET @date = '2020-10-01'; SELECT DATE_ADD(@date, INTERVAL 2 DAY) AS 'DATE_ADD', ADDDATE(@date, INTERVAL 2 DAY) AS 'ADDDATE 1', ADDDATE(@date, 2) AS 'ADDDATE 2';
Result:
+------------+------------+------------+ | DATE_ADD | ADDDATE 1 | ADDDATE 2 | +------------+------------+------------+ | 2020-10-03 | 2020-10-03 | 2020-10-03 | +------------+------------+------------+
But if we try to use the second form on ADD_DATE()
, we get an error:
SET @date = '2020-10-01'; SELECT DATE_ADD(@date, 2) AS 'DATE_ADD 2';
Result:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2) AS 'DATE_ADD 2'' at line 1
This is because this function doesn’t support that syntax.