Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL order by 0 then largest

Tags:

sorting

mysql

I am trying to do a mysql sort that displays 0 first and then by the largest number.

My current mysql statement returns

10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0, 0, 0, 0

But I would like to get this

0, 0, 0, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2, 1

Is it possible to build a MySQL query that orders an integer from largest to smallest with 0 at the beginning?

like image 787
Robert E. McIntosh Avatar asked Dec 09 '22 15:12

Robert E. McIntosh


2 Answers

Try this order by statement:

order by val = 0 desc, val desc

The first part is a boolean that evaluates to "1" when the value is 1 and otherwise 0. The second orders the rest of the values in descending order.

like image 110
Gordon Linoff Avatar answered Dec 11 '22 09:12

Gordon Linoff


you have to use 2 filters

select * from mytable
order by mycolumn=0 desc, mycolumn desc
like image 41
Thanos Darkadakis Avatar answered Dec 11 '22 08:12

Thanos Darkadakis