MySQL Custom Sort
February 1st, 2007 Posted in Code
Here's something neat. If you want your SQL results in an order that's not alphabetical or numerical, this little bit of code will allow you to specify what order you want your fields to appear.
MySQL:
-
ORDER BY CASE
-
WHEN `col` = 'item' THEN 1
-
WHEN `col` = 'thing' THEN 2
-
WHEN `col` = 'stuff' THEN 3
-
WHEN `col` = 'boom' THEN 4
-
ELSE 5
-
END
Note that these are not in alphabetical order. You can still add other sort fields before and after this case. Pretty neat!
August 25th, 2008 at 7:33 pm
Great tip, this is exactly what I was looking for! I just wanted to pull one category to the top of the list that fell in the middle in alpha sort and this tip worked perfectly.
Thanks for posting, I have learned MySQL through a very incremental approach and this is a great addition to my arsenal.
Regards,
Bryan
December 11th, 2008 at 1:48 pm
Genius. Thanks.