0

Why when i use order by seriq asc and have numbers like "10000" "100000" "97000"

script show me the results:

1: 10000
2: 100000
3: 97000

?

Mike Christensen
  • 88,082
  • 50
  • 208
  • 326

4 Answers4

3

because they are stored in your column as strings

1- try to change the column seriq from VARCHAR/CHAR to INT.

2- You can use CAST() to convert from string to int. e.g. SELECT CAST('123' AS SIGNED);

echo_Me
  • 37,078
  • 5
  • 58
  • 78
0

Your seriq column must be a numeric column for values to be sorted numerically. If it's a text column, values will be sorted in alphabetical order as per their collation. For example:

CREATE TABLE Test
(
   Foo int  
);

INSERT INTO Test VALUES (10000);
INSERT INTO Test VALUES (100000);
INSERT INTO Test VALUES (97000);

select * from Test order by Foo asc;

Fiddle

Community
  • 1
  • 1
Mike Christensen
  • 88,082
  • 50
  • 208
  • 326
0

The quick fix is to have MySQL convert the string to a numeric value in the ORDER BY clause.

Change your query to:

ORDER BY seriq+0 ASC

Note that MySQL will attempt to convert any string to a numeric value, reading characters up to the first "invalid" character, e.g. '123A' will be converted to a numeric value 123.

spencer7593
  • 106,611
  • 15
  • 112
  • 140
0

Changing the column type to int is the best solution as it will give you the best data storage and performance. However, if that is not an option, the following workaround is possible:

select * from foo order by seqid+0

This forces a type cast of the order by column to int, and the sort happens numerically.

Sasha Pachev
  • 5,162
  • 3
  • 20
  • 20