9

I have created a native query with interval. The query works fine when i hard code day in query:

@Query(value="select * from orders where created_date  < clock_timestamp() - interval ' 5 days'",nativeQuery=true)

But when i provide data with @Param like this:

@Query(value="select * from orders where created_date  < clock_timestamp() - interval :day 'days'",nativeQuery=true)
List<Order> getData(@Param("day") String day)

I got this error:

Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "$1"

2 Answers 2

23

You can't provide a value for an interval like that. You need to multiple the parameter value with your interval base unit:

"select * from orders 
where created_date  < clock_timestamp() - (interval '1' day) * :days"

As you are dealing with days, you can simplify that to:

"select * from orders 
where created_date  < clock_timestamp() - :days"

Another option is the make_interval() function. You can pass multiple parameters for different units.

"select * from orders 
where created_date  < clock_timestamp() - make_interval(days => :days)"

The notation days => ... is a named parameter for a function call. If the variable represents hours, you could use make_interval(hours => ..)

Sign up to request clarification or add additional context in comments.

8 Comments

Thanks for your help
what about interval '2 hour'... ?
You mean (interval '1' hour) * :hours ?
I tried the (interval '1 hour') * :hours, but my results are incorrect, although there is no exception anymore. stackoverflow.com/questions/57795441/…
Nice, and works in a Query annotation, but does not work in a Formula annotation. There, I ended up having make_interval(0,0,0,1) to specify a 1-day interval.
|
7

One solution is provided in this entry Spring Boot Query annotation with nativeQuery doesn't work in Postgresql

Basically:

@Query(value="select * from orders where created_date  < clock_timestamp() - ( :toTime )\\:\\:interval",nativeQuery=true)

'toTime' is a Param from your repository and could be days, hour, minute... etc(review interval doc in Postgres) @Param("toTime") String toTime

3 Comments

This is what solved my issue - escaping the double colons since JPA was interpreting that as substitution variables
This works in a Query annotation but does not work in a Formula annotation. In the Formula annotation, I ended up writing it as make_interval(0,0,0,1) to specify a 1 day interval.
@sergio could you please tell me how i can pass my sql correctly in the query annotation : DELETE FROM TABLE WHERE my_column < (NOW() - INTERVAL '30 minutes') and i want to pass '30 minutes' as a param in my java method

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.