Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

sql

mysql

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!

like image 992
ufk Avatar asked Mar 24 '11 10:03

ufk


People also ask

How do I sort by a specific column in SQL?

The ORDER BY statement in SQL is used to sort the fetched data in either ascending or descending according to one or more columns. By default ORDER BY sorts the data in ascending order. We can use the keyword DESC to sort the data in descending order and the keyword ASC to sort in ascending order.

Which MySQL clause is used to arrange the data in a particular order?

We can sort results in ascending or descending order with an ORDER BY clause in Select statement.

How do I sort items in MySQL?

Use the ORDER BY clause to sort the result set by one or more columns. Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order. The ORDER BY clause is evaluated after the FROM and SELECT clauses.

How do I change the order of data in MySQL?

An "ALTER TABLE ORDER BY" statement exist in the syntaxes accepted by MySQL. According to the documentation, this syntax: - only accept *one* column, as in "ALTER TABLE t ORDER BY col;" - is used to reorder physically the rows in a table, for optimizations.


2 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 
like image 184
RichardTheKiwi Avatar answered Sep 19 '22 13:09

RichardTheKiwi


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 
like image 35
Dumitrescu Bogdan Avatar answered Sep 20 '22 13:09

Dumitrescu Bogdan