3

I have the following values in my rows (they should be ordered like this);

**CLASS_CODE**
6A
6B
6C
10A
10B
10C

Well if I do a simple ORDER BY CLASS_CODE, I will get first 10x then 6x values.

So I use ORDER BY (CLASS_CODE+0), this orders them correctly so that 6x comes first, but it does not order them accordingly to chars as well.

What would be the correct way to order by, so I can get the correct order as shown above?

a'r
  • 35,921
  • 7
  • 66
  • 67
Adnan
  • 25,882
  • 18
  • 81
  • 110
  • 3
    because MySQL will do only a string comparision 1 is before 6. What you want is a natural sort (like in PHP i.e. for arrays). I don't know if that is possible in MySQL – rabudde Nov 25 '11 at 09:00

4 Answers4

3

There is something here : http://www.carlos-roque.com/2011/04/19/sorting-characters-and-numbers-in-mysql/

I can't test it right now, but I believe something like that can be a nice hack :

SELECT CLASS_CODE as hack ... ORDER BY (CLASS_CODE+0)ASC, hack ASC

Maybe try to turn it around.

If that's a fail, here is some discussion about sorting in a natural fashion : Natural Sort in MySQL

Community
  • 1
  • 1
BuZz
  • 16,318
  • 31
  • 86
  • 141
3

As long as you only use a single letter at the end of the field values, then you can use the following:

ORDER BY (class_code+0), right(class_code, 1)
a'r
  • 35,921
  • 7
  • 66
  • 67
  • I only have one letter at the end. Thank you for your solution. – Adnan Nov 25 '11 at 09:13
  • The example by the OP indeed leads to assume that there's always one character after a number, but in general that may not be true. And even if it is, you still don't have to extract the rightmost character. Once you've got the order by `(class_code+0)`, the subgroups can be ordered simply by `class_code`. – Andriy M Nov 25 '11 at 09:13
0

Sorry for the late reply. But it may help someone.

You have to implement Natural Sorting. To sort it using PHP, you can use natsort() function.

You can achieve natural sorting through MySQL also which is simple enough. For ex:

ORDER BY LENGTH(class_code), class_code
0

I have had this scenario and I use the CAST function. In this case ORDER BY CAST(class_code AS DECIMAL)

Simon Mbatia
  • 301
  • 1
  • 3
  • 9