1

I'm trying to get a list of some products' model & all models are alphanumeric.

I tried

ORDER BY CAST(field_name AS UNSIGNED) 

and

ORDER BY field_name + 0

and

ORDER BY LENGTH(field_name)

and some other ways.

They works for most of them but there are some values that doesn't match the order.

The result I get is like

EAG-75

EAG-110

...

ESCG-500

ESCG-600

...

EYG-40

EYG-55

...

EMG-440

EMG-20

EMG-27

...

EAG-100

...

I don't understand what is causing this.

Please help.

Thanks in advance

3
  • how do you want them sorted? give an example. If you order alphabetically, EAG-110 comes before EAG-75 Commented Jan 24, 2012 at 15:27
  • I want them to be sorted alphanumericcaly like EAG-75 , EAG-100 , EAG-110 , EMG-20... Commented Jan 24, 2012 at 15:33
  • @Onur: I think you actually means "per non-numeric prefix, sort numerically" Commented Jan 24, 2012 at 15:38

2 Answers 2

5

You need to sort the 2 bits separately if you want a correct numeric sort per non-numeric prefix

ORDER BY
    -- sort by prefix only
    LEFT(MyCol, INSTR(col, '-')-1),  
    -- sort numerically within prefix
    CAST(SUBSTRING(MyCol, INSTR(col, '-')+1) AS UNSIGNED) 
Sign up to request clarification or add additional context in comments.

3 Comments

As long as all your model numbers are in the format AAA-##, you won't get much better than this solution.
Hi, it works perfect in that format but if there are some other results like AAAA# in the same query, then it doesn't work well for 4 character results, how can I fix it? thanks in advance
oh I think I fixed it by changing -1 to -2 in LEFT(MyCol, INSTR(col, '-')-1)
0

Would ORDER BY LENGTH(field_name), field_name work better for you?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.