Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Varchar Order By 1

Status
Not open for further replies.

BigHans

Technical User
May 10, 2011
2
GB
Hi!

After a vast amount of hunting I've come to no resolution to my dilemma. I have a varchar(20) table column containing values similar to this:

Alpha 1
Alpha 2
Alpha 3
Alpha 10
Alpha 12
Beta 1
Beta 2
Beta 3
Beta 15
...
...

With a straight forward ORDER BY field it outputs the following:

Alpha 1
Alpha 10
Alpha 12
Alpha 2
Alpha 3
Beta 1
Beta 15
Beta 2
Beta 3
...
...

I tried ORDER BY field+0, which returned exactly the same thing. I have also tried CAST to no avail.

Please can someone suggest what I should try next?

Thanks in advance
 
You really need two columns here, so that the number can be treated as such. You can split the column for the ORDER BY clause by looking for the embedded space (assuming that it is always there):
Code:
...
ORDER BY
  LEFT(column, LOCATE(' ', column)) -- the alpha part
, CONVERT(SUBSTRING(column, LOCATE(' ', column) + 1), UNSIGNED) -- the number
HTH
Simon
 
Ideally I would have two columns but I do have other values in this column (int, decmial etc). For this ORDER BY instance the selected field will always have a space so, thank you for your help here it works perfectly!
 
instead of LOCATE and SUBSTR, in mysql you can use SUBSTRING_INDEX
Code:
ORDER 
    BY SUBSTRING_INDEX(column,' ',1) 
     , CAST(SUBSTRING_INDEX(column,' ',-1) AS UNSIGNED)

r937.com | rudy.ca
Buy my new book Simply SQL from Amazon
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top