MySQL DATE_SUB() Function
In MySQL, the DATE_SUB()
function subtracts a date or time interval from the specified date or datetime and returns the result.
DATE_SUB()
Syntax
Here is the syntax of MySQL DATE_SUB()
function:
DATE_SUB(date, INTERVAL value unit)
Parameters
date
- Required. A data or datetime value or expression.
value
- Required. A date/time interval. Both positive and negative numbers are allowed.
unit
- Required. The unit of the date/time interval.
The unit of the data/time interval can be one of the following values:
MICROSECOND
SECOND
MINUTE
HOUR
DAY
WEEK
MONTH
QUARTER
YEAR
SECOND_MICROSECOND
MINUTE_MICROSECOND
MINUTE_SECOND
HOUR_MICROSECOND
HOUR_SECOND
HOUR_MINUTE
DAY_MICROSECOND
DAY_SECOND
DAY_MINUTE
DAY_HOUR
YEAR_MONTH
Return value
The DATE_SUB()
function subtracts a date or time interval from the specified date or datetime value and returns the result. The result’s date type is determined by the parameters:
- If
date
is aDATE
value andunit
isYEAR
,MONTH
orDAY
, it returns aDATE
value. - If
date
is aDATE
value andunit
isHOURS
,MINUTES
orSECONDS
, it returns aDATETIME
value. - If
date
is aDATETIME
value, it returns aDATETIME
value. - If
date
is aTIME
value andunit
isYEAR
,MONTH
orDAY
, it returns aDATETIME
value. - If
date
is aTIME
value and the computation involves only theHOURS
,MINUTES
andSECONDS
parts , it returns aTIME
value. (MySQL 8.0.28 and later) - Otherwise it returns a string value.
DATE_SUB()
Examples
Here are some examples of the DATE_SUB()
function.
Example 1
SELECT
DATE_SUB('2020-06-10', 10),
DATE_SUB('2020-06-10', -10)\G
DATE_SUB('2020-06-10', 10): 2020-05-31
DATE_SUB('2020-06-10', -10): 2020-06-20
Example 2
SELECT
DATE_SUB('2020-06-10', INTERVAL 10 DAY),
DATE_SUB('2020-06-10', INTERVAL 10 HOUR)\G
DATE_SUB('2020-06-10', INTERVAL 10 DAY): 2020-05-31
DATE_SUB('2020-06-10', INTERVAL 10 HOUR): 2020-06-09 14:00:00
Example 3
SELECT
DATE_SUB('2020-06-10 10:00:00', INTERVAL 10 HOUR),
DATE_SUB('2020-06-10 10:00:00', INTERVAL 10 MINUTE)\G
DATE_SUB('2020-06-10 10:00:00', INTERVAL 10 HOUR): 2020-06-10 00:00:00
DATE_SUB('2020-06-10 10:00:00', INTERVAL 10 MINUTE): 2020-06-10 09:50:00
Example 4
SELECT
DATE_SUB(CURDATE(), INTERVAL 10 HOUR),
DATE_SUB(NOW(), INTERVAL 10 MINUTE)\G
DATE_SUB(CURDATE(), INTERVAL 10 HOUR): 2022-04-10 14:00:00
DATE_SUB(NOW(), INTERVAL 10 MINUTE): 2022-04-11 08:56:43
Here, we used the CURDATE()
function to get the current date and used the NOW()
function to get the current datetime.