welcome.

MySQL Custom Sort

Posted: February 1st, 2007 | Author: briandichiara | Filed under: 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.

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!


2 Comments on “MySQL Custom Sort”

  1. 1 Bryan said at 7:33 pm on August 25th, 2008:

    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

  2. 2 Jamie Tibbetts said at 1:48 pm on December 11th, 2008:

    Genius. Thanks.


Leave a Reply