I want to sort the following data items in the order they are presented below (numbers 1-12):
1 2 3 4 5 6 7 8 9 10 11 12
However, my query - using order by xxxxx asc
sorts by the first digit above all else:
1 10 11 12 2 3 4 5 6 7 8 9
Any tricks to make it sort more properly?
Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:
A1 534G G46A 100B 100A 100JE
etc....
Thanks!
update: people asking for query
select * from table order by name asc
People use different tricks to do this. I Googled and find out some results each follow different tricks. Have a look at them:
Edit:
I have just added the code of each link for future visitors.
Alpha Numeric Sorting in MySQL
Given input
Expected output
Query
Natural Sorting in MySQL
Given input
Expected Output
Query
Sorting of numeric values mixed with alphanumeric values
Given input
Expected Output
Query
Hope this helps
Just do this:
Appending the +0 will mean that:
0, 10, 11, 2, 3, 4
becomes :
0, 2, 3, 4, 10, 11
This type of question has been asked previously.
The type of sorting you are talking about is called "Natural Sorting". The data on which you want to do sort is alphanumeric. It would be better to create a new column for sorting.
For further help check natural-sort-in-mysql
SELECT s.id, s.name, LENGTH(s.name) len, ASCII(s.name) ASCCCI FROM table_name s ORDER BY ASCCCI,len,NAME ASC;
I had some good results with