Skip to content
Advertisement

Coalesce with a conditional expression

The following query works when executed in SequelPro:

SELECT * FROM friend_computer LEFT JOIN computer m ON computer_id = m.id LEFT JOIN computer_status ms ON m.id = ms.computer_id JOIN friend_account pa ON friend_account_id = pa.id WHERE friend_account_id = 1 ORDER BY coalesce(ms.last_connect_time < ms.last_disconnect_time, -1) asc;

But in Hibernate, I keep getting a syntax error for the below:

String sql2 = "SELECT pm FROM FriendComputer pm LEFT JOIN FETCH pm.computer m JOIN FETCH pm.friendAccount pa " +
        "WHERE pm.friendAccount.id = :friendId AND pm.computer = m  ORDER BY coalesce((m.computerStatus.lastDisconnectTime < m.computerStatus.lastConnectTime),-1 ) " + sortOrder;
         org.hibernate.query.Query q = session().createQuery(sql2).setParameter("friendId", friendId);

The syntax error is due to the coalesce function. I can’t find any online resources about how to use an expression inside coalesce.

Advertisement

Answer

What are you trying to do? An explicit case would at least provide clarity:

order by (case when ms.last_connect_time < ms.last_disconnect_time then 2
               when  ms.last_connect_time >= ms.last_disconnect_time 1
               else 0
          end)
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement