Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Postgres Interval not working with native spring data JPA query

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"

like image 938
Ajit Soman Avatar asked May 03 '17 18:05

Ajit Soman


2 Answers

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 => ..)

like image 99
a_horse_with_no_name Avatar answered Oct 16 '22 14:10

a_horse_with_no_name


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

like image 36
Sergio Gonzalez Avatar answered Oct 16 '22 13:10

Sergio Gonzalez