Wednesday, September 12, 2007

Customized Order By Sequence - A Small Hack

What if you have to customize the sequence of order by clause on a column. Say, you have a integer column 'weight' that can have values ranging from 1 to 5 and you want to get the rows in the sequence 4,2,5,1,3. So what do you do? Here is a simple trick using the field function.

   1: mysql> SELECT * FROM table ORDER BY FIELD(weight, 4, 2, 5, 1, 3);
Now what does it do. Field function returns the index of the first argument in the rest of the list. So, effectively the order by logic will be the same, just that the values that are being ordered are generated on the fly.

Other approach can be to use CASE.. WHEN .. END statement as mentioned in the MySQL Documentation. The above code can be rewritten as:

   1: mysql> SELECT *, CASE 
   2:     -> WHEN weight = 1 THEN 4
   3:     -> WHEN weight = 2 THEN 2
   4:     -> WHEN weight = 3 THEN 5
   5:     -> WHEN weight = 4 THEN 1
   6:     -> WHEN weight = 5 THEN 3
   7:     -> END AS weight_custom
   8:     -> FROM table
   9:     -> ORDER BY weight_custom;
But I'm a little biased towards the first approach due to its simplicity. Though it's a matter of personal choice.

Such requirements are rare, just a food for thought.

Hope this blog was helpful to you. Keep posting your comments.

4 comments:

Shaun said...

Thanks!
Been looking for hours for this!

alex said...

You saved me a lot of time! Thank you!

ramsiva said...

Very nice.... thanks a lot

Anonymous said...

HI dear,

Thanks for this article.

it really helpful for me.
You saves my plenty of time with the help of this mysql order by method

thanks again