SQL order string as number SQL order string as number mysql mysql

SQL order string as number


If possible you should change the data type of the column to a number if you only store numbers anyway.

If you can't do that then cast your column value to an integer explicitly with

select col from yourtableorder by cast(col as unsigned)

or implicitly for instance with a mathematical operation which forces a conversion to number

select col from yourtableorder by col + 0

BTW MySQL converts strings from left to right. Examples:

string value  |  integer value after conversion--------------+--------------------------------'1'           |  1'ABC'         |  0   /* the string does not contain a number, so the result is 0 */'123miles'    |  123 '$123'        |  0   /* the left side of the string does not start with a number */


Another way, without using a single cast.

(For people who use JPA 2.0, where no casting is allowed)

select col from yourtableorder by length(col),col

EDIT: only works for positive integers


Another and simple way

ORDER BY ABS(column_name)