Question

SQL for sorting boolean column as true, null, false

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.

 45  74807  45
1 Jan 1970

Solution

 48

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

2013-12-20

Solution

 47

Not beautiful, but should work:

   ... order by (case when f1 then 1 when f1 is null then 2 else 3 end) asc
2010-05-13