MySQL – Sort results in order by list

I needed today to sort a result set in MySQL after a list of id’s given. My original query was: SELECT uid, pid FROM pages WHERE uid IN (15,17,21,87);...

I needed today to sort a result set in MySQL after a list of id’s given. My original query was:

SELECT uid, pid FROM pages WHERE uid IN (15,17,21,87);

So the exact order of records i needed was 15, 17, 21, 87. But i wasn’t getting the results in this order. After digging around for a while i found the solution which is quite easy! I needed to alter my query a little bit to receive the desired order of results

SELECT uid, pid FROM pages WHERE uid IN (15,17,21,87) ORDER BY FIELD(uid, 15,17,21,81);

And voila, it works!

1 Comment

Leave a Reply

*

*


  • Jannik
    22 September 2011 at 21:42

    This can be done a lot easier. Just use ORDER BY uid [DESC|ASC] (desc-> order descending, asc-> order ascending)