I have a column with values like below after ordering by it’s column name (equipment_no) in ASC and was wondering how to sort it properly as shown in the next list.
SELECT equipment_no FROM fas_details WHERE equipment_no LIKE 'T%' ORDER BY equipment_no
Please do tell me your suggestions. Thank you.
How mysql sorts
T - AG - 01
T - AG - 02
T - AG - 07
T - AG - 08
T - AG - 09
T - AG - 10
T - AG - 100
T - AG - 101
T - AG - 102
T - AG - 103
T - AG - 104
T - AG - 11
T - AG - 12
T - AG - 13
How I want it to be
T - AG - 01
T - AG - 02
T - AG - 07
T - AG - 08
T - AG - 09
T - AG - 10
T - AG - 11
T - AG - 12
T - AG - 13
T - AG - 100
T - AG - 101
T - AG - 102
T - AG - 103
T - AG - 104
Answer:
Try this:
Order By CAST(SUBSTRING_INDEX(equipment_no,'-',-1) AS UNSIGNED)
or you can try using RIGHT like
CAST(RIGHT(equipment_no, (CHARINDEX('-',REVERSE(equipment_no),0))-1) AS UNSIGNED)
***
Use substring_index function to get the number from string and then cast it to unsigned integer in order by :
SELECT equipment_no FROM fas_details WHERE equipment_no LIKE 'T%'
ORDER BY cast(substring_index(equipment_no,'-',-1) as unsigned)
https://stackoverflow.com/questions/35288902/how-to-sort-an-alphanumeric-column-in-mysql?noredirect=1&lq=1