skip to Main Content

I want to make a prepared statement for a query that takes a number and calculates an interval. Something along these lines:

SELECT col FROM t1 WHERE createtime < (NOW() - INTERVAL ? DAY)

However, this doesn’t work, because the interval should be a string literal:

SELECT col FROM t1 WHERE createtime < (NOW() - INTERVAL '3 DAY')

But, how should I do this then, without having to concat a query together?

3

Answers


  1. As you observe, the syntax INTERVAL '3' DAY allows only a string constant, not a parameter. Use make_interval:

    ... WHERE createtime < current_timestamp - make_interval(days => ?)
    
    Login or Signup to reply.
  2. Maybe this:

    select NOW() - (YOUR_NUMBER::text||' DAYS')::interval
    
    Login or Signup to reply.
  3. You may multiply the one day interval with the bind variable parameter

    select * from t1
    where createtime < now() - interval '1' day * ?
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search