I have a PostgreSQL table of items with an optional ordering field:
CREATE TABLE tasks (
id integer PRIMARY KEY DEFAULT nextval('f_seq'),
f_id integer REFERENCES fixins,
name text NOT NULL,
sort integer
);
I want tasks that have no sort
value to sort after all others, with one exception: if sort = -1
I want it to sort after those. So, for example, given these values:
id | f_id | name | sort
---+------+----------+-------
1 | 1 | zeta | -1
2 | 1 | alpha | 1
3 | 1 | gamma | 3
4 | 1 | beta | 2
5 | 1 | delta |
6 | 1 | epsilon |
I want them to sort as: alpha
, beta
, gamma
, delta
, epsilon
, zeta
.
I know that I can use ORDER BY COALESCE(sort,99999)
to order null values after non-nulls, but how can I get that special -1
value to come after those?