Explain Codes LogoExplain Codes Logo

Mysql add days to a date

sql
date-manipulation
mysql-functions
sql-queries
Nikita BarsukovbyNikita Barsukov·Sep 17, 2024
TLDR

Add days using DATE_ADD(). Here's a quick example:

SELECT DATE_ADD('2021-03-01', INTERVAL 10 DAY);

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!

SELECT DATE_ADD(field, INTERVAL 2 DAY) FROM your_table;

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:

UPDATE your_table SET date_column = DATE_ADD(date_column, INTERVAL 2 DAY) WHERE id = 161;

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.
SELECT ADDDATE('2021-03-01', INTERVAL 10 DAY);
  • No calendar needed: Add days to the current date with CURDATE().
SELECT ADDDATE(CURDATE(), INTERVAL 10 DAY);
  • 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 the INTERVAL 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!