7

I have a query that's something like this

select days, date(date_event)  + interval '10' day from tbl_user_marketing_program as programtable 

Now in place of the '10', I want to add the value present in the "days" column. How can I do that?

I tried select user_id, date(date_event) + interval user_id day from tbl_user_marketing_program as programtable

then I got the below error

ERROR: syntax error at or near "day" LINE 1: ...ect user_id, date(date_event) + interval user_id day from t...

1

4 Answers 4

17

Unfortunately the "number" for an interval can't be an arbitrary expression, it has to be a string constant (which is a strange choice). You need to use a little workaround:

select days, date(date_event) + (days * interval '1' day) 
from tbl_user_marketing_program as programtable 

But date + integer is also directly supported and the unit is days in that case. So you can als write:

select days, date(date_event) + days 
from tbl_user_marketing_program as programtable 
Sign up to request clarification or add additional context in comments.

Comments

3

You can quote '10 days':

select days, date(date_event)  + interval '10 days'
from tbl_user_marketing_program as programtable 

SqlFiddleDemo

If you want add variable/column use:

datetime + variable * INTERVAL '1 day'

select days, date(date_event)  + column * interval '1 day'
from tbl_user_marketing_program as programtable 

SqlFiddleDemo

2 Comments

No, interval '10' day is correct - it's the way an interval literal is defined in the SQL standard and it is supported by Postgres
@a_horse_with_no_name I misunderstood question. Anyway +1 for your answer
1

If I understand the question correctly, casting to an interval is the solution (instead of useing interval your_column days)

select days, date(date_event)  + (user_id::integer || ' day')::interval from tbl_user_marketing_program as programtable

that converts the user_id to integer, concatenates with 'day', and casts the whole string to interval. That interval you can add to your date.

Comments

0

If days column is integer, first cast it as interval type:

select days, date(date_event)  + cast(days as interval day(7))
from tbl_user_marketing_program as programtable 

4 Comments

cast(days as day(7)) is invalid
It is? How do you cast as interval types in Postgresql?
There is no function day(x) in SQL (or Postgres). See Lad's and my answer for a correct way to specify an interval
Oops, typo... Does cast(days as interval day(7)) work?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.