Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ORDER BY CASE WHEN ... ELSE ... END in PostgreSQL

I have my ORDER BY clause as following:

...
ORDER BY CASE WHEN boolean_column is true  THEN text_column END ASC,
         CASE WHEN boolean_column is false THEN text_column END DESC

Is it somehow possible to replace the second CASE in an ELSE? It feels odd to have two conditions instead of a regular if else/when else as you normally would do.

like image 767
forever-living Avatar asked Dec 11 '22 07:12

forever-living


2 Answers

You can use this trick to shorten the logic:

ORDER BY (CASE WHEN boolean_column THEN text_column END) ASC,
         text_column DESC

It is still two order by keys though.

like image 70
Gordon Linoff Avatar answered Dec 18 '22 14:12

Gordon Linoff


If the type of text_column is numeric. you can try this.

ORDER BY CASE WHEN boolean_column is true THEN text_column 
              ELSE -1 * text_column END ASC
like image 42
Serkan Arslan Avatar answered Dec 18 '22 14:12

Serkan Arslan