Subtract month and day mysql
If you're in a rush to subtract a month and four days from a date in MySQL, type the following:
Hit Enter, and congratulations! You've officially traveled one month and four days into the past. ๐
What's happening under the hood?
Dealing with different lengths of months
When you use DATE_SUB()
, MySQL thinks about each month's length. For example, if you tried to subtract a month from January 31, MySQL would return December 31, since it took into account that February doesn't have 31 days.
Leap Years are no problem
If you're dealing with a leap year and subtract a month from March 1, MySQL will return February 1, not February 29th. How can one SQL function be so smart?
Time doesn't remain still
In some cases you might need to consider the time as well as the date, in which case you should use NOW()
. However, if you only care about the date, stick with CURDATE()
.
Using the other tools in your SQL toolbox
Subtract without subtraction? Learn this one trick!
Did you know you can use the DATE_ADD()
function to subtract from a date? Simply use a negative interval. Opticians hate this one weird trick!
A little extra subtraction
For those occasions when subtracting one interval is not enough, you can use nested DATE_ADD functions.
Avoiding invalid dates
Sometimes when subtracting, you can end up with a date that doesn't exist. With DATE_SUB()
MySQL has got you covered:
Pitfalls to avoid
Corner cases
When dealing with months like February, or leap years, you should brace for some surprise corners MySQL can turn. Embrace the turns to ensure your SQL stays tight.
Considering compatibility
Before you go all "guns blazing" with these functions, make sure to check the MySQL version you're using to ensure compatibility.
The question of performance
Do bear in mind the performance implications for large datasets. Indexing or caching may be needed when using such functions in high-load environments.
Was this article helpful?