Close

2023-10-08

DATE_ADD() And DATE_SUB() Functions for MySQL

DATE_ADD() And DATE_SUB() Functions for MySQL

MySQL provides the DATE_ADD() and DATE_SUB() functions to perform date arithmetic.

Here are some examples to illustrate their usage:

1. DATE_ADD()

The DATE_ADD() function is used to add a specified time interval to a date.

Syntax:

DATE_ADD(date, INTERVAL value unit)

Example:

To add five days to the current date:

SELECT DATE_ADD(CURDATE(), INTERVAL 5 DAY);

To add three months to a specific date:

SELECT DATE_ADD('2023-01-01', INTERVAL 3 MONTH);

2. DATE_SUB()

The DATE_SUB() function is used to subtract a specified time interval from a date.

Syntax:

DATE_SUB(date, INTERVAL value unit)

Example:

To subtract five days from the current date:

SELECT DATE_SUB(CURDATE(), INTERVAL 5 DAY);

To subtract three months from a specific date:

SELECT DATE_SUB('2023-01-01', INTERVAL 3 MONTH);

Note: The unit can be values like SECOND, MINUTE, HOUR, DAY, WEEK, MONTH, QUARTER, or YEAR.

Always test your SQL queries in a safe environment before applying them to production databases.