| Subcribe via RSS

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:
  1. ORDER BY CASE
  2.     WHEN `col` = 'item' THEN 1
  3.     WHEN `col` = 'thing' THEN 2
  4.     WHEN `col` = 'stuff' THEN 3
  5.     WHEN `col` = 'boom' THEN 4
  6.     ELSE 5
  7. END

Note that these are not in alphabetical order. You can still add other sort fields before and after this case. Pretty neat!

2 Responses to “MySQL Custom Sort”

  1. Bryan Says:

    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. Jamie Tibbetts Says:

    Genius. Thanks.


Leave a Reply

Preview: