Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySql - order by string value first

Tags:

mysql

I've got the following table Foobar that looks like this:

+----+-------------+
| ID | Description |
+----+-------------+
| 12 | aab         |
+----+-------------+
| 13 | fff         |
+----+-------------+
| 14 | fff         |
+----+-------------+
| 15 | xab         |
+----+-------------+

What I would like is to print out all the descriptions in order. However I would first of all like the values "fff" to be right at the top. In other words the output should be as follows: fff, fff, aab, xab.

So a simple: "SELECT foobar.description FROM foobar ORDER BY foobar.description ASC" will not work.

like image 698
John Crawford Avatar asked Oct 15 '13 10:10

John Crawford


People also ask

How do I sort by string in SQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I get the first character of a string in MySQL?

To fetch the first alphabet from the strings, use LEFT(). This method allows you to return characters from the left of the string.

Does order matter in MySQL?

So the order of columns in a multi-column index definitely matters. One type of query may need a certain column order for the index. If you have several types of queries, you might need several indexes to help them, with columns in different orders.

How do I sort alphabetically in MySQL?

Use the ASC option to sort the result set in ascending order and the DESC option to sort the result set in descending order.


2 Answers

In MySQL this works

SELECT foobar.description 
FROM foobar 
ORDER BY foobar.description <> 'fff',
         foobar.description ASC

But generally you can also use a case

SELECT foobar.description 
FROM foobar 
ORDER BY case when foobar.description = 'fff' then 1 else 2 end,
         foobar.description ASC
like image 154
juergen d Avatar answered Oct 31 '22 23:10

juergen d


select foobar.description from foobar
order by case when foobar.description = 'fff' then 1 else 2 end,
foobar.description asc 
like image 27
Deepak Rai Avatar answered Oct 31 '22 23:10

Deepak Rai