MySQL DATE_SUB Function

Tuesday, December 27, 2011

tags SQL

The MySQL DATE_SUB function subtracts a custom time interval from a date.

Employees Table

employeeIDemployeeNameretirementDate
1000John Smith2025-12-03
1001Fred White2031-10-12
1002Jane Scott2028-05-01
1003Samuel Williams2021-01-03

In this example, we want to determine the year before an employee is scheduled to retire.


Syntax

DATE_SUB(date,INTERVAL interval format)


FORMAT
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


Example
SELECT employeeName as [Employee Name], DATE_SUB(retirementDate INTERVAL 1 YEAR) as [Eligible for Early Retirement]
FROM employees


Results

Employee NameEligible for Early Retirement
John Smith2024
Fred White2030
Jane Scott2027
Samuel Williams2020

Did you find the page informational and useful? Share it using one of your favorite social sites.

Recommended Books & Training Resources

SQL Cookbook Head First SQL: Your Brain on SQL A Learners Guide