MySQL – Sort results in order by list

Total
0
Shares

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

Leave a Reply

Your email address will not be published. Required fields are marked *

You May Also Like