MySQL DATE_SUB() Function
The DATE_SUB()
function in MySQL is used to subtract a specified time interval from a date value. This is extremely helpful for calculating past dates or for data analysis involving time periods.
DATE_SUB(): Definition and Usage
This function allows you to easily adjust dates backward by subtracting various time units, such as days, months, years, hours, minutes, and seconds. It's a flexible tool for working with temporal data.
Syntax
Syntax
DATE_SUB(date, INTERVAL value unit)
Parameter Values
Parameter | Description |
---|---|
date |
The starting date or datetime value. This is required. |
value |
The numerical value representing the amount of the time interval to subtract. Positive values subtract, negative values add. This is required. |
unit |
The unit of the time interval. Options:
|
Examples
Subtracting Days
Subtracting 10 days from June 15th, 2017.
Syntax
SELECT DATE_SUB("2017-06-15", INTERVAL 10 DAY);
Output
2017-06-05
Subtracting Minutes
Subtracting 15 minutes from a datetime value.
Syntax
SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 15 MINUTE);
Output
2017-06-15 09:19:21
Subtracting Hours
Subtracting 3 hours from a datetime value.
Syntax
SELECT DATE_SUB("2017-06-15 09:34:21", INTERVAL 3 HOUR);
Output
2017-06-15 06:34:21
Adding Months (using negative interval)
Adding 2 months to a date (by subtracting a negative interval).
Syntax
SELECT DATE_SUB("2017-06-15", INTERVAL -2 MONTH);
Output
2017-08-15