mysql SQL: specific item to be first and then to sort the rest of the items

I can't access a MySQL now to test, so it might be reversed... but you can use the fact that Booleans also sort, and that you can have several sort fields.

SELECT ... ORDER BY id != 5, id

(you might have to write id = 5, I can't remember if TRUEs sort before or after FALSEs.)

EDIT: Oh, I just read that you don't care about the order of the rest, in which case I heartily recommend @Richard's answer.


select id,name 
from friends 
order by id=5 desc

(given you don't care about order of the rest, otherwise, e.g. rest by id asc)

select id,name 
from friends 
order by id=5 desc, id asc

Try this:

select id,name 
from friends 
order by case when id=5 then -1 else id end

if you have more then one you can do:

select id,name 
from friends 
order by case when id in (5,15,25) then -1 else id end,id

Tags:

Mysql

Sql