I was writing a MySQL database query and ran into an interesting challenge where my result set needed to be ordered in a predefined order to meet business logic requirements. Typically the ORDER BY clause will sort using numeric or alphabetical order. This is pretty limiting if you want to define an enumeration of values that should provide the sort order. A simple example of this is using ORDER BY on a column that stores numbers as strings, like ‘one’, ‘two’, ‘three’, ‘four’, etc. Using ORDER BY on this field will yield a result set ordered by those strings in alphabetical order, not the integer values that they represent.

  

The way to order this using the order ‘one’, ‘two’, ‘three’, ‘four’ is to use the MySQL Field() function. Using Field() it is possible to define the order which will return the index of the string position that matches string. The MySQL documentation is incomplete with using Field() in conjunction with ORDER BY, but this example illustrates the syntax.

  

The strings used to ORDER BY do not need to represent numbers. In my challenge I needed to order the results by a status column that contained a number of different strings and business rules dictated the order of importance for the MySQL query in question.

Leave a Reply

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