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

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

Posted by: admin November 1, 2017 Leave a comment

Questions:

Lets say I have the table below.

I want to get all the friends, but I want the id 5 to be the first item in the list. I don’t care about the order that I receive the rest of the items.

The desired query result will be:

friends
-------

id    name

5     nahum
1     moshe
2     haim
3     yusuf
4     gedalia
6     dana

How can I do this?

using Mysql 5.1.x.

Thanks!

Answers:
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

Questions:
Answers:

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

Questions:
Answers:

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.

Questions:
Answers:

This is a little ugly because it has code duplication, but it does the trick:

select .... where id = 5 
union
select .... where not id = 5