How do I add a column to a date in Postgres?

2019-09-17 06:53发布

问题:

I’m using Postgres 9. I’m trying to do date math with a column in my table that is an integer. I’m trying this:

select current_timestamp + interval age || ' years'
from my_table
where age is not null
limit 5;
ERROR:  syntax error at or near "||"
LINE 1: select current_timestamp + interval age || ' years' from rac...

What is the proper way to write this? I’m trying to add the age column, which is in years, to the current timestamp (now)?

回答1:

Multiply your integer with 1-year intervals and add it to the timestamp:

SELECT current_timestamp + interval '1 year' * age
FROM   my_table
WHERE  age IS NOT NULL
LIMIT  5;

Related:

  • Query using two column values to create range