Dynamic (Column Based) Interval
I usually multiply the number by interval '1 day'
or similar, e.g.:
select now() + interval '1 day' * a.number_of_days from a;
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;
I prefer this way. I think its pretty easy and clean.
In postgre you need interval
to use +
operator with timestamp
select (3||' seconds')::interval;
select now()+ (10||' seconds')::interval,now();
where you can use seconds,minutes...days,months... and you can replace the numbers to your column.
select now()+ (column_name||' seconds')::interval,now()
from your_table;
To creating intervals those based on column values, I recommend to add two columns in your table. For example, column "period_value"::INT4 and column "period_name"::VARCHAR. Column "period_name" can store the following values:
- microsecond
- milliseconds
- second
- minute
- hour
- day
- week
- month
- quarter
- year
- decade
- century
- millennium
+--------------+-------------+ | period_value | period_name | +--------------+-------------+ | 2 | minute | +--------------+-------------+
Now you can write:
SELECT NOW() - (period_value::TEXT || ' ' || period_name::TEXT)::INTERVAL FROM table;
Use make_interval()
SELECT NOW() + make_interval(days => a.number_of_days) AS "The Future Date"
FROM a;
But in general it might be a better idea to use a column defined as interval
, then you can use any unit you want when you store a value in there.