MySQL DATE_SUB() Function
The DATE_SUB() function in MySQL is used to subtract an interval of time from a specified date or datetime value. It’s particularly useful when working with date calculations, such as finding dates in the past relative to a given date.
Syntax
date: The starting date or datetime value from which the interval will be subtracted.INTERVAL expr unit: Specifies the amount and type of time to subtract.expr: A number representing the interval value.unit: The unit of time (e.g.,DAY,MONTH,YEAR).
Supported Units
| Unit | Description |
|---|---|
MICROSECOND | Microseconds |
SECOND | Seconds |
MINUTE | Minutes |
HOUR | Hours |
DAY | Days |
WEEK | Weeks |
MONTH | Months |
QUARTER | Quarters (3 months) |
YEAR | Years |
Examples
1. Subtracting Days from a Date
To subtract 7 days from 2025-01-12:
Output:
2. Subtracting Months from a Date
To subtract 2 months from 2025-01-12:
Output:
3. Subtracting Years from a Date
To subtract 5 years from 2025-01-12:
Output:
4. Subtracting Time from a Datetime
To subtract 3 hours and 15 minutes from a datetime value 2025-01-12 15:30:00:
Output:
5. Combining Multiple Subtractions
You can nest DATE_SUB() functions to perform multiple subtractions. For example, to subtract 1 year and 2 months from 2025-01-12:
Output:
Practical Applications
Generating Past Date Reports: Use
DATE_SUB()to filter records older than a specific time.Calculating Expiry Dates: Subtract trial periods to find expiration dates.
Analyzing Historical Data: Subtract years or months to compare historical data trends.
Best Practices
- Validate Input: Ensure the
dateparameter is valid to avoid unexpected results. - Use CURDATE() or NOW(): For dynamic date subtraction, use built-in functions like
CURDATE()(for date) orNOW()(for datetime). - Optimize Queries: When using
DATE_SUB()inWHEREclauses, ensure the column used is indexed for better performance.
Conclusion
The a DATE_SUB() function is a powerful tool for date manipulation in MySQL. It allows you to subtract intervals of time from a given date or datetime, making it ideal for dynamic calculations in applications such as reports, audits, and data analysis. By understanding its syntax and capabilities, you can effectively handle date-based operations in your database.

