The SUBDATE() function in MySQL is used to subtract a specified time interval from a date or datetime value. It can be used to subtract years, months, days, hours, minutes, seconds, etc., from a given date.
Syntax:
SUBDATE(date, interval)
- date: The date or datetime value from which the interval will be subtracted.
- interval: The value you want to subtract, specified as a number followed by a unit (such as 'DAY', 'MONTH', 'YEAR', etc.).
Example 1: Subtracting Days
SELECT SUBDATE('2024-12-23', 5);
This will return 2024-12-18, which is 5 days before 2024-12-23.
Example 2: Subtracting Months
SELECT SUBDATE('2024-12-23', INTERVAL 3 MONTH);
This will return 2024-09-23, which is 3 months before 2024-12-23.
Example 3: Subtracting Multiple Units
SELECT SUBDATE('2024-12-23', INTERVAL 2 YEAR);
This will return 2022-12-23, which is 2 years before 2024-12-23.
Example 4: Using SUBDATE() with a DATETIME
SELECT SUBDATE('2024-12-23 10:30:00', INTERVAL 1 HOUR);
This will return 2024-12-23 09:30:00, which is 1 hour before 2024-12-23 10:30:00.
Notes:
- The second argument can also be a string representing the interval, like
'5 DAY'or'3 MONTH', rather than usingINTERVAL. - If the date is invalid or the interval is not correct, MySQL will return an error or a NULL result.
Let me know if you'd like more examples or explanations!
No comments:
Post a Comment