Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQlite conditional order

I have this query:

  select id,number,name 
    from objects 
order by case number when 0 then 1 else -1 end asc

The database is a database of objects with numbers. If an object doesn't have a number than its number is 0. I want to sort by number ascending, with the exception of when the number is 0, in which case, sort descending.

The query above seems to sort by ID, the default sorting order.

Thank you.

like image 299
Francisc Avatar asked Sep 14 '26 01:09

Francisc


1 Answers

Close, but you forgot to sort by number as well:

  SELECT id,number,name 
    FROM objects 
ORDER BY CASE number WHEN 0 THEN 1 ELSE 0 END, number;
like image 195
mechanical_meat Avatar answered Sep 17 '26 06:09

mechanical_meat