Reputation: 712
Hi have a result which returns as follows
ORDER BY ProductCode ASC
CU522-15
CU522-17
CU522-18
CU522-19
CU522-4
I am trying to get cu522-4 to be first and not last . I can't change the ProductCode as it needs to match another system. Any Ideas ?
Upvotes: 1
Views: 53
Reputation: 1269873
In the event that your product code prefix is not always the same length, you can do:
order by substring_index(ProductCode, '-', 1),
substring_index(ProductCode, '-', -1) + 0;
The + 0
does a numeric conversion of the value, which is what you want for sorting.
Upvotes: 0
Reputation: 6066
Try with
SELECT * FROM `mytable` ORDER BY LENGTH(ProductCode), ProductCode
CU522-4 will be first because it has less characters
The others will be sorted normally
Upvotes: 2
Reputation: 874
Going on the assumption it's always '-' this should work:
SELECT *
FROM table
ORDER BY CAST(SUBSTRING(ProductCode,LOCATE('-',ProductCode)+1) AS SIGNED)
Use POSITION to find the '-', SUBSTRING to grab the number after it, and CAST to make it a comparable value.
Upvotes: 3