Search code examples
mysqlnatural-sort

How do you sort fields which have numbers in a mathematical order


The following users are present in our database..

create table users (id, name);

name [u1, u2, u3, u4, u5, u6, u7, u8, u9, u10, u11, ...]

If the above field is sorted in an ascending fashion, the output is as follows..

u1, u10, u11, u2, u3, u4 ...

Is it possible to sort this in the order at the top (i.e. list all single digits, double digits ...)


Solution

  • Try:

    SELECT *
    FROM users
    ORDER BY CAST(SUBSTR(name FROM 2) AS UNSIGNED)