15

I looking for some tweak in mysql ordering , I normally select record from table and then order the record by Name(varchar) ASC but the number is always come first

here some example of my question (note. mysql sort the record with 0-9 first)

SELECT name FROM list ORDER BY name ASC
record returned:
1 star
2 star
9 slice
Ape
Age
Beg
Bell
Fish
Zoo

What i want is the alphabet order come first then follow by number

Desired output

Ape
Age
Beg
Bell
Fish
Zoo
1 star
2 star
9 slice
Old Pro
  • 24,624
  • 7
  • 58
  • 106
Leon Armstrong
  • 1,285
  • 3
  • 16
  • 41

5 Answers5

34

Use the following ORDER BY clause:

ORDER BY IF(name RLIKE '^[a-z]', 1, 2), name
Barmar
  • 741,623
  • 53
  • 500
  • 612
10

Ref this

SELECT name FROM list ORDER BY name * 1 ASC

Edited

SELECT name FROM list ORDER BY name * 1, name ASC
Community
  • 1
  • 1
Salil
  • 46,566
  • 21
  • 122
  • 156
0

You can try something like this:

SELECT 
    name 
FROM 
    list 
ORDER BY 
    IF(name REGEXP '^[0-9]', CONCAT('zz',name),name) ASC

So if your name start with a digit you concatenate 'zz' in the beginning (so that it will be last)

Stephan
  • 8,000
  • 3
  • 36
  • 42
0

This is what worked for me in Rails with a POSTGRESQL DB

.order(Arel.sql("SUBSTRING(LOWER(name), '^[A-Za-z].*'), SUBSTRING(LOWER(name), '^[0-9]+')::FLOAT"))  

                       
Surbhit Rao
  • 625
  • 6
  • 14
-2

Try this..

It simple one to get your answer

SELECT name  from list ORDER BY (name +0) ASC ,name ASC
Ganesh Rengarajan
  • 2,006
  • 13
  • 26