简体   繁体   中英

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.

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

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.

You can do the sorting at first, getting the position of each record, and then choose the sorting direction

WITH rows_with_positions AS (
    SELECT
        boolean_column,
        text_column,
        ROW_NUMBER() OVER (ORDER BY text_column) AS position,
        .. 
    FROM your_table
)
SELECT text_column, ..
FROM rows_with_positions
ORDER BY
    CASE WHEN boolean_column
        THEN position
        ELSE -1 * position
        END
    ASC

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM