2

Given a VARCHAR column called title with the following SELECT title FROM table ORDER BY title results:

Alpha 11
Alpha 2
Beta 1
Beta 11
Beta 2

I would like this to be in the "correct" order of

Alpha 2
Alpha 11
Beta 1
Beta 2
Beta 11

Is there a way to do this?

Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83
kylex
  • 14,178
  • 33
  • 114
  • 175
  • 1
    alter your table to have two columns for that, Field1 which contains *ALPHA*, *BETA*,.. and `Field2` which contains the numeric part. and you can now easily sort it, `ORDER BY Field1 ASC, Field2 ASC` becomes life easier. – John Woo Jan 19 '13 at 03:34

3 Answers3

2

Try this:

SELECT title ,
  SUBSTRING_INDEX(title, '', 1) as title_str,
  SUBSTRING_INDEX(title, ' ', -1) + 0 as title_num
FROM table 
ORDER BY title_str, 
  title_num
John Conde
  • 217,595
  • 99
  • 455
  • 496
1

This is called Natural Order sorting. Unfortunately there is no such sort algorithm built-in to MySQL, so your most reliable bet would be to create a UDF to do it for you.

However, this question has an interesting answer:

Here is a quick solution:

SELECT title
FROM table
ORDER BY LENGTH(title), title
Community
  • 1
  • 1
Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
0

Try this:

SELECT title 
FROM tablename 
ORDER BY SUBSTRING_INDEX(title, ' ', 1), 
         CAST(SUBSTRING_INDEX(title, ' ', -1)  AS UNSIGNED);
Saharsh Shah
  • 28,687
  • 8
  • 48
  • 83