Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic (Column Based) Interval

Tags:

postgresql

How do I add a dynamic (column based) number of days to NOW?

SELECT NOW() + INTERVAL a.number_of_days "DAYS" AS "The Future Date"  FROM a; 

Where a.number_of_days is an integer?

like image 461
explodes Avatar asked Mar 10 '11 22:03

explodes


2 Answers

I usually multiply the number by interval '1 day' or similar, e.g.:

select now() + interval '1 day' * a.number_of_days from a; 
like image 129
araqnid Avatar answered Sep 20 '22 23:09

araqnid


I know this is a year old, but if you need to use a column to specify the actual interval (e.g. 'days', 'months', then it is worth knowing that you can also CAST your string to an Interval, giving:

SELECT now()+ CAST(the_duration||' '||the_interval AS Interval) 

So the the original question would become:

SELECT now() + CAST(a.number_of_days||" DAYS" AS Interval) as "The Future Date" FROM a; 
like image 40
Paul S Avatar answered Sep 22 '22 23:09

Paul S