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.
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.