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
…[Read more]