Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL - ordering by something not ASC or DESC

Say I have a table of flowers with associated colors. Is it possible to get a list of flowers and order them by, say, Yellow first, then Blue, then Red. Basically, I want to specify a list of values and order the result by those values. Possible?

like image 714
StackOverflowNewbie Avatar asked May 12 '11 06:05

StackOverflowNewbie


3 Answers

You could use FIND_IN_SET:

ORDER BY FIND_IN_SET(column, 'Yellow,Blue,Red')

..or the ANSI CASE statement:

ORDER BY CASE column
           WHEN 'Yellow' THEN 1
           WHEN 'Blue' THEN 2
           WHEN 'Red' THEN 3
         END
like image 123
OMG Ponies Avatar answered Sep 19 '22 11:09

OMG Ponies


You can add a field in colors table for sort_order and and provide values according to the sort requirement. In the query you can use ORDER BY sort_order ASC

I am expecting that you want to order it according to a dynamic requirement not explicitly for these three colors mentioned. This will allow you complete flexibility to manage the sort order.

like image 34
Deepu S Nath Avatar answered Sep 21 '22 11:09

Deepu S Nath


My choice would be using the FIELD(str, str1, str2, ...) function.

Returns the index (position) of str in the str1, str2, str3, ... list. Returns 0 if str is not found.

So you could use the return value to order your list of results:

ORDER BY FIELD (color, 'Yellow', 'Blue', 'Red')

If you want to reverse the order, just add DESC.

like image 26
kapa Avatar answered Sep 20 '22 11:09

kapa