Mysql add days to a date
⚡TLDR
Add days using DATE_ADD()
. Here's a quick example:
This spits out 2021-03-11
, 10 days post the date you designated.
Adding days in select queries
Need to increment a date field within a selection query? No problem!
This will list all dates from your_table
, but each shifted 2 days forward in time.
Updating specific rows: The world isn't static
And neither is your data. Here's how you can update a date field for a particular row:
This is insanely useful, because:
- You can target a specific row with its ID or other distinct identifier
- It's always wise to test this on a backup data set before applying it to live data; because prevention is better than cure!
- If you're dealing with multiple time zones, remember to consider the effects on the dates, unless you're a fan of time travel.
Shall I compare thee to a... MySQL function?
DATE_ADD()
doesn't suit your fancy? Got ya covered!
- Meet
ADDDATE()
: It does the same job but differently.
- No calendar needed: Add days to the current date with
CURDATE()
.
- Mind the Clock: If your application cares about time, verify that your date manipulations don't mess with the time component.
Potential hiccups and tumbles
My Spidey senses tell me you should be aware of:
- Date Overflow: Adding to end of a month? MySQL handles the roll over gracefully.
- Leaping Over: Yes, MySQL takes into account February 29 in leap years.
- Invalid Dates: Always ensure adding days doesn't result in senseless dates like
0000-00-00
.
Tips, tricks, and wizardry
Before we part ways, a few words of wisdom:
- Syntax Matters: Make sure you type
DATE_ADD(column, INTERVAL X DAY)
just like that - parentheses and theINTERVAL
keyword are non-negotiable! - Updates Are Serious: Double-check your WHERE clause before updating to avoid unwanted mass modifications.
- Backup Is Your Friend: Always keep a backup ready. You never know when you need a time machine!
Linked
Linked
Was this article helpful?