2

I have table like

CREATE TABLE IF NOT EXISTS example 
(id INT NOT NULL AUTO_INCREMENT,
name VARCHAR(100) NOT NULL,
primary key ( id ))

I insert to table 20 record from 1 -> 20 like

id | name
1  | example 0
2  | example 1
...
20 | example 19

I do query like

SELECT *
FROM `example`
ORDER BY `name` DESC 

But results are

id | name
10 | example 9
9  | example 8
...
1  | example 0

I think that is

id | name
20 | example 19
19 | example 18
...
1  | example 0

How can I do what i think. Thanks

LookAtMeNow
  • 261
  • 1
  • 5
  • 15

5 Answers5

2

It is a string sort, not a numeric one

ASCII wise, descending, '9' is before '20' as expected. THis can also be thought of as '9 ' (trailing space) being compared to '20'

String sorting is character-wise.

gbn
  • 422,506
  • 82
  • 585
  • 676
1

Use SUBSTRING to grab the number after the space with LOCATE and then do ORDER BY should work while using CAST.

SELECT   *
FROM     example
ORDER BY CAST(SUBSTRING(name,LOCATE(' ',name)+1) AS SIGNED) DESC
Iron3eagle
  • 1,077
  • 7
  • 23
0
SELECT *
FROM `example`
ORDER BY CAST(name AS UNSIGNED)desc;

fiddle

Praveen Prasannan
  • 7,093
  • 10
  • 50
  • 70
0

It's doing alpha ordering because it's a string.

Example 2 is after Example 1000.

Some options You could split it in to two fields names and number You could do a lot of messing about with String functions to split it up for a sort You could add leading zeros Example 0002 is before Example 1000.

Tony Hopkinson
  • 20,172
  • 3
  • 31
  • 39
-1

You are ordering by the name which will result in an alphebetic order. Try

    ORDER BY id desc;
June Lewis
  • 355
  • 1
  • 6
  • 28
  • The ID is just an auto-incremented field, which should not be used for sorting. In this specific case, OP is asking to sort by name. Sorting by a different field that only accedentally has the right order, does not solve the underlying problem. – GolezTrol Jul 26 '13 at 13:49