Replace integer except value 0 with sql

I am trying to get an ordered list of rows from my MYSQL database table based on the integer value "place".

SELECT * FROM mytable ORDER BY place; 

This works fine, except that all rows with place = 0 should appear at the end of the table.

So if my table is:

 name place ---- ----- John 1 Do 2 Eric 0 Pete 2 

he must become:

 name place ---- ----- John 1 Do 2 Pete 2 Eric 0 
+6
sql database mysql
source share
3 answers
 SELECT * FROM myTable ORDER BY place>0 DESC, place 

is a solution without CASE

+4
source share
 order by case when place = 0 then 1 else 0 end asc, place asc 

this way you get all nonzero orders first.

+6
source share
 SELECT * FROM myTable ORDER BY CASE place WHEN 0 THEN 9999 ELSE place END 

This approach implies that we knew that 9999 (or some other value) is larger than all the possible values ​​in the place column.

Alternatively, we can sort by two values, as in:

  ORDER BY CASE place WHEN 0 THEN 0 ELSE -1 END, place 
+2
source share

All Articles