3

I have these CB1-15 values however I want to order them by... CB1-15 but currently it goes CB1, CB10, CB11 etc.

This is how my table looks...

CB    Description   File Path

CB1   New Product   new.png
CB10            
CB11            
CB12            
CB13            
CB14            
CB15            
CB2   Best Seller   best.png
CB3         
CB4         
CB5         
CB6         
CB7         
CB8         
CB9         

Thanks for helping :)

2
  • 1
    Just so I'm clear. is the sample data one column or multiple? Commented Sep 24, 2016 at 3:35
  • @JohnCappelletti it's been answered - however if anyone searches it later on iv'e updated the post to show its columns Commented Sep 25, 2016 at 2:36

3 Answers 3

6

Use the below script.

  SELECT * 
  FROM  YourTable
  ORDER BY CAST(Replace(YourColumn,'CB','')as INT)
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you :) Much appreciated!
2

It's a little unclear if that data is in multiple columns or a single string. Here's one method that should work in both cases:

select *
from yourtable
order by cast((substring(yourfield, 3, 2)) as int)

The key is using cast to order by an int instead of the string.

2 Comments

Thank you ever so much sir :)
This doesn't work for CB100 so you have to use the length of value instead of 2 by replacing CB, So I would say @Unnik's solution work better.
0

Another simple method do do the ordering:

order by len(col), col

And if you want descending:

order by len(col) desc, col desc

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.