Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list 2.0 #2443

Closed
jakob-fiegerl opened this issue May 3, 2019 · 1 comment

Comments

@jakob-fiegerl
Copy link

jakob-fiegerl commented May 3, 2019

I've got the following code which selects all distinct pets and orders them by the status (alive desc and lastModified desc)

 private final JPAQueryFactory query;
query.select(pet)
        .distinct()
        .from(pet)
        .orderBy(pet.status.when("alive").then(1).otherwise(0).desc())
        .orderBy(pet.lastModifiedDateTime.desc())
        .fetch();

which leads to:

org.postgresql.util.PSQLException: ERROR: for SELECT DISTINCT, ORDER BY expressions must appear in select list

BUT without the distinct OR the orderBy(pet.status..) the query is just fine. But why??

query.select(pet)
        .from(pet)
        .orderBy(pet.status.when("alive").then(1).otherwise(0).desc())
        .orderBy(pet.lastModifiedDateTime.desc())
        .fetch();

QueryDSL Version 4.2.1

@jwgmeligmeyling
Copy link
Member

This is simply a limitation of PostgreSQL:

select distinct * from (values ('a', true), ('b', true), ('c', false)) as pet(name, alive)
    order by case when pet.alive then 1 else 0 end asc ;
ERROR:  for SELECT DISTINCT, ORDER BY expressions must appear in select list
LINE 1: ...true), ('c', false)) as pet(name, alive) order by case when ...       

As the error mentions, it can be resolved by adding the order by expression to the select clause:

select distinct *,  case when pet.alive then 1 else 0 end  from (values ('a', true), ('b', true), ('c', false)) as pet(name, alive) order by case when pet.alive then 1 else 0 end asc ;
 name | alive | case 
------+-------+------
 c    | f     |    0
 a    | t     |    1
 b    | t     |    1
(3 rows)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants