How do I add times to a date with SQL?

 

Yes, that’s right.

However, apart from the ones we discussed a while agoVertica and MySQL also offer a few more ways on which you can fall back if you’d like to have simpler syntax.

These are:

DB Function Comment
Vertica add_months(timestamp, unit) adds months to a date
MySQL adddate(timestamp, unit) adds days to a date
MySQL addtime(timestamp, unit) adds seconds to a date
MySQL subdate(timestamp, unit) subtracts days from a date
MySQL subtime(timestamp, unit) subtracts seconds from a date
MySQL period_add(yyyymm, unit) adds months to a year-month period*

*super handy if used with dynamic year-month periods and you can easily get those by using the concat() function

-----------------------------------------Vertica---------------------------------------------------------------------------
select
Now(),
add_months(Now(), 1) as 1MonthFromNow,
add_months(Now(),-1) as 1MonthAgo,
add_months(Now(), 5) as 5MonthsFromNow,
add_months(Now(),-5) as 5MonthsAgo,
add_months(Now(), 8) as 8MonthsFromNow,
add_months(Now(),-8) as 8MonthsAgo
-------------------------------------------MySQL----------------------------------------------------------------------------
select
now(),
date(adddate(now(), 5)) as 5DaysFromNow,
time(addtime(now(), 5)) as 5SecondsFromNow,
date(subdate(now(), 5)) as 5DaysAgo,
time(subtime(now(), 5)) as 5SecondsAgo,
#fixed input month
period_add(201801, 3) as 3MonthFromYM,
period_add(201801,-3) as 3MonthAgo,
concat(year(now()), #get current year month
case when month(now()) < 10 then concat(0, month(now())) else month(now()) end) as ThisYM,
#dynamic input month
period_add(concat(year(now()), #get current year month
case when month(now()) < 10 then concat(0, month(now())) else month(now()) end), 5) as 5MonthsFromNow
now() |5DaysFromNow |5SecondsFromNow |5DaysAgo |5SecondsAgo |3MonthFromYM |3MonthAgo |ThisYM |5MonthsFromNow |
--------------------|-------------|----------------|-----------|------------|-------------|----------|-------|---------------|
2017-10-18 16:17:29 |2017-10-23 |16:17:34 |2017-10-13 |16:17:24 |201804 |201710 |201710 |201803 |

Happy SQL-ing!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.