10:45 am
0
600
views

Order mySQL results in a predefined set list order

Okay, it's tricky to put in a title what I'm getting at here, so sorry if the title is a little vague :).

What I want to show here is how to order by records in a custom way in mySQL. So for arguments sake, take a look at the below query:

select * from my_table
where id in (2,1,4,3,5)

Now if I wanted the results to come out in that exact order 2,1,4,3,5 it's tricky to do without having some data in the database that will output it in that order (e.g. a position column or whatever).

Well this is where the find_in_set() string function comes into play! To do exactly what I mentioned above, I'd edit the statement like:

select * from my_table
where id in (2,1,4,3,5)
order by find_in_set(id,'2,1,4,3,5')

The above tells mySQL to return the results in the order of id's 2,1,4,3,5, voila!

One note of caution, ensure you do not have spaces in your list, otherwise the desired effect will not work, e.g. the follow will not return the correct order: find_in_set(id,'2, 1, 4, 3, 5'), definitely worth remembering, because I was scratching my head when I encountered this the first time around (as ColdFusion decided it wanted to add the spaces to my var).