16

SELECT test_column FROM test_table ORDER BY test_column gives me this:

1
12
123
2
3

Why not:

1
2
3
12
123

How can I sort strings like numbers?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
CDT
  • 10,165
  • 18
  • 66
  • 97

6 Answers6

23

Try

SELECT test_column 
FROM test_table 
ORDER BY cast(test_column as int)

But you should look into changing the column types to the correct ones.

JBrooks
  • 9,901
  • 2
  • 28
  • 32
8

This worked for me:

ORDER BY cast(test_column as SIGNED)

here, cast function convert value from string to integer(SIGNED) then it applied ORDER BY. https://dev.mysql.com/doc/refman/8.0/en/cast-functions.html

vineet
  • 13,832
  • 10
  • 56
  • 76
  • An explanation would be in order. Please respond by [editing (changing) your answer](https://stackoverflow.com/posts/32844785/edit), not here in comments (***without*** "Edit:", "Update:", or similar - the answer should appear as if it was written today). – Peter Mortensen Jul 18 '21 at 12:38
  • added cast function brief explanation. – vineet Jul 18 '21 at 15:51
3

Check if the type of the column is varchar or something similar. It looks like it is being ordered by string value, not by numeric value. If the column only contains numbers it should better be of type int.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Dennis Traub
  • 50,557
  • 7
  • 93
  • 108
2

The sort is working. It's a lexicographic sort (alphabetical). It appears that that column has a text (char, varchar, ...) type, so the ordering you'll get is textual and not numeric.

If you want a numerical sort, use a numeric column type (e.g. int). (Or cast the column appropriately.)

Mat
  • 202,337
  • 40
  • 393
  • 406
0

I think , we need to do the cast as part of the select statement , because if we use distinct then casting in the order by statement does not work:

  SELECT cast(test_column as int) as test_column 
    FROM test_table
ORDER BY test_column

and

  SELECT DISTINCT cast(test_column as int) as test_column 
    FROM test_table 
ORDER BY test_column
buddemat
  • 4,552
  • 14
  • 29
  • 49
0

Change the field type in the database table to int, because it's treated as string that is why

J. Chris Compton
  • 538
  • 1
  • 6
  • 25