Sorting text fields in numeric order in MySQL

Added on: Tuesday 24th November 2009

Here are several ways of sorting text fields in numerical order in a MySQL query.

Normally you wouldn't do this because you will have defined the field as numeric when setting up the table.

However, if you want to create an application with as much flexibility as possible there will be times when you might need this.

I often use it in our CMS because it allows 'user defined fields' in any record type.

The data is stored in an additional table which references the correct record and field.

As all the data for any user defined field is stored in the same table it has to be stored as text in order to allow the maximum number of 'types' of data.

Any validation is done on the input form so effectively you can have different data types.

So an example might be that a 'Price' field is added to the standard content record for listing products (the full e-commerce module has a separate table for products but a small site wouldn't have this) and this would need to be sorted in ascending or descending order.

If for example you had several entries such as 5.00, 10.99, 1.45 and 6.35 then the SQL statement:

SELECT user_value FROM table ORDER BY user_value

would return 1.45, 10.99, 5.00 and 6.35.

There are several ways you can sort this (excuse the pun!).

SELECT user_value FROM table ORDER BY (user_value+0)

SELECT user_value FROM table ORDER BY CAST(user_value, INT)


SELECT user_value FROM table ORDER BY LPAD(user_value,10,'0')

All of the above work and I don't think it really matters which is used. I would guess that the overhead is slightly greater for the last two (although an internal conversion probably has to be done for the first one) but I haven't tested them against each other.

Be careful with the last one which in the example above pads each record with zeros until the result is 10 characters long - if the original value is more than ten characters it will get truncated.