Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering based on number value in a string from SQL

Tags:

sql

sql-server

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 :)

like image 702
Adam91Holt Avatar asked Dec 07 '25 13:12

Adam91Holt


2 Answers

Use the below script.

  SELECT * 
  FROM  YourTable
  ORDER BY CAST(Replace(YourColumn,'CB','')as INT)
like image 81
Unnikrishnan R Avatar answered Dec 09 '25 14:12

Unnikrishnan R


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)
  • SQL Fiddle Demo

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

like image 41
sgeddes Avatar answered Dec 09 '25 14:12

sgeddes



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!