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!
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.
We can sort results in ascending or descending order with an ORDER BY clause in Select statement.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With