27
votes

My table has three boolean fields: f1, f2, f3. If I do

SELECT * FROM table ORDER BY f1, f2, f3

the records will be sorted by these fields in the order false, true, null. I wish to order them with null in between true and false: the correct order should be true, null, false.

I am using PostgreSQL.

5

5 Answers

38
votes

Not beautiful, but should work:

   ... order by (case when f1 then 1 when f1 is null then 2 else 3 end) asc
31
votes

A better solution would be to use

f1 DESC NULLS LAST

if you're okay with the order true, false, nil ( I guess the important part of your question was, like in my situation now, to have the not-true vaules together)

https://stackoverflow.com/a/7621232/1627888

6
votes

you could do also as follows:

order by coalesce(f1, FALSE), coalesce(f1, TRUE), ...

If f1 is TRUE, you get: TRUE, TRUE
If f1 is NULL, you get: FALSE, TRUE
If f1 is FALSE, you get: FALSE, FALSE

which corresponds to the sorting order you want.

0
votes

You can sort any finite set of things in any order by using a case statement to map the elements to the counting numbers ...

-1
votes

It is also possible to do as follows:

... ORDER BY (CASE WHEN f1 IS NOT NULL THEN f1::int * 2 ELSE 1 END) DESC