Sorting null values after all others, except special

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;

db<>fiddle here
Old sqlfiddle

Leave a Comment