Natural Sorting for MySQL

MySQL doesn’t provide a way to perform natural sorting on a string, so if you have numbers in your data you may get results like this

Product 110
Product 120
Product 13
Product 140

There are a lot of hacks available, but all of the ones I’ve seen only work in specific circumstances. The only comprehensive solution I found to do the sorting in MySQL is Drupal’s natsort module.¬†You don’t need to be running Drupal to use it, just issue the queries that create the function and it’s dependencies, and you can then call it in your regular queries. But, it requires MySQL 5, so if you’re working on an older server and your data doesn’t work with one of the hacks, then you’ll probably just have to do the natural sorting in your scripting language, using something like PHP’s natsort().

Leave a Reply

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