Home > Software design >  PostgreSQL Union query not working in JPA
PostgreSQL Union query not working in JPA

Time:03-27

The below PostgreSQL query works correct in pgAdmin.

(select * from posts where id = 1) union (select * from posts);

but when written in Spring Data JPA it doesn't work.

   @Query(value = "(select * from posts where id = 1) union (select * from posts)",
            nativeQuery = true)
    Page<Post> getPosts(Pageable pageable);

It gives an exception

Caused by: org.postgresql.util.PSQLException: ERROR: syntax error at or near "where"
  Position: 15

i want to have a union of the two select statements but the union query is not working in JPA.

CodePudding user response:

How about

select
  *
from (
  (select * from posts where id = 1)
  union
  (select * from posts)
) as subquery

as your query? This is a query where the framework can append its WHERE clause without a syntax error.

  • Related