Sorting null values after all others, except special

后端 未结 2 441
忘掉有多难
忘掉有多难 2020-11-29 13:49

I have a PostgreSQL table of items with an optional ordering field:

CREATE TABLE tasks (
  id     integer  PRIMARY KE         


        
相关标签:
2条回答
  • 2020-11-29 14:31

    Simpler:

    SELECT *
    FROM   tasks
    ORDER  BY (sort IS NOT DISTINCT FROM -1), sort;
    

    How?

    Postgres has a proper boolean type (unlike some other RDBMS). You can order by it just like by any other data type. And it can be NULL like any other data type. Default sort order is:

    FALSE (0)
    TRUE (1)
    NULL
    

    (sort IS NOT DISTINCT FROM -1) evaluates to FALSE for all values except -1 - which evaluates TRUE and sorts last. Just add sort as secondary ORDER BY item.

    Equivalent alternative:

    SELECT *
    FROM   tasks
    ORDER  BY (sort IS DISTINCT FROM -1) DESC, sort;
    

    SQL Fiddle.

    0 讨论(0)
  • 2020-11-29 14:46
    SELECT name FROM tasks
      WHERE f_id=1
      ORDER BY
        CASE COALESCE(sort,88888)
          WHEN -1 THEN 99999
          ELSE         COALESCE(sort,88888)
        END,
        id;
    

    Still looking for a more elegant way to only do that coalesce once, without selecting it.

    0 讨论(0)
提交回复
热议问题