I have a PostgreSQL table of items with an optional ordering field:
CREATE TABLE tasks (
id integer PRIMARY KE
Simpler:
SELECT *
FROM tasks
ORDER BY (sort IS NOT DISTINCT FROM -1), sort;
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.