Postgres INTERVAL using value from table

后端 未结 3 1315
余生分开走
余生分开走 2020-12-18 14:00

If I want to add 5 days to a date, I can do it using the INTERVAL function:

select create_ts + interval \'5 days\' from abc_company;
         


        
3条回答
  •  无人及你
    2020-12-18 14:18

    You just need a working type cast. This kind is standard SQL.

    select current_timestamp + cast((num_of_days || ' days') as interval)
    from abc_company;
    

    This is an alternative syntax, peculiar to PostgreSQL.

    select current_timestamp + (num_of_days || ' days')::interval
    from abc_company;
    

    I prefer not trying to remember the third kind of type cast supported by PostgreSQL, which is the function-like syntax.

    select current_timestamp + "interval" (num_of_days || ' days')
    from abc_company;
    

    Why? Because some function names have to be quoted; interval is one of them.

    Also, the names interval, time, and timestamp can only be used in this fashion if they are double-quoted, because of syntactic conflicts. Therefore, the use of the function-like cast syntax leads to inconsistencies and should probably be avoided.

提交回复
热议问题