Sorting null values after all others, except special

后端 未结 2 440
忘掉有多难
忘掉有多难 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.

提交回复
热议问题