Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

order by clause on status in my sql

Tags:

sql

mysql

I am doing a sorting on a table to show the records with status having 3 first then status having 4 and then 1.

in current table this is the output

id    status
 1     3
 2     4
 3     4
 4     3
 5     1

now when i apply the query

select * from table order by model.status desc 

the output is:

id    status
 2     4
 3     4
 1     3
 4     3
 5     1

what i want actually the below output. first with status 3 then with status 4 and then with status 1. How to achieve the below output

id    status
 1     3
 4     3
 2     4
 3     4
 5     1
like image 219
JN_newbie Avatar asked Sep 06 '25 03:09

JN_newbie


1 Answers

instead of a magic 9999999 number, you can use ~0, which represents the maximum possible value for big int... should be enough ;)

order by (case when status = 1 then ~0 else status end) 

other solution, without any magic number

order by status = 1 , status

which will sort by a "boolean" (0 or 1 in DB) first, then by status

like image 174
Raphaël Althaus Avatar answered Sep 07 '25 23:09

Raphaël Althaus