Solved

# Sort by Alphanumeric

Posted on 2005-04-15
Medium Priority
1,260 Views
I would like to sort my records by their alphanumeric values.  A table that I have lists House Unit Numbers such as:

10-A
100-C
121-B
20
234-D
356-H
40-C
500-867
512-876
and so forth.

They sort exactly as I have typed it up there but I want it to sort by what is to the left of the "-" first and then sort what is to the right of the "-" second.  I found an article on microsoft's website here - http://support.microsoft.com/?kbid=209632. which does similar to what I want but not exactly.  Some of these Unit Numbers do NOT have alpha characters and some do not have a "-".  Those in the example show some that have dashes and some that have dashes but no alpha.

Here is how I want to sort.

10-A
20
40-C
100-C
121-B
234-D
356-H
500-867
512-876

Can someone provide me some assistance?  Thanks.
0
Question by:molard
• 2
• 2

LVL 28

Expert Comment

ID: 13790732
SELECT * FROM YourTable
ORDER BY CAST(LEFT(YourColumn, ISNULL(NULLIF(CHARINDEX('-', YourColumn) - 1, -1), LEN(YourColumn))) AS INT)
0

Author Comment

ID: 13790868
Thank you for the reply.  Your suggestion worked great however is there a way that I can get lets say the number 34 to come before 34-A.  Right now it sorts the ones with the "-" before the regular plain numbers.  Thanks again.
0

LVL 28

Accepted Solution

rafrancisco earned 500 total points
ID: 13790879
SELECT * FROM YourTable
ORDER BY CAST(LEFT(YourColumn, ISNULL(NULLIF(CHARINDEX('-', YourColumn) - 1, -1), LEN(YourColumn))) AS INT), YourColumn

0

Author Comment

ID: 13790936
That did great.  Thanks again!
0

## Featured Post

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

One of the most important things in an application is the query performance. This article intends to give you good tips to improve the performance of your queries.
MSSQL DB-maintenance also needs implementation of multiple activities. However, unprecedented errors can hamper the database management. In that case, deploying Stellar SQL Database Toolkit ensures fast and accurate database and backup repair as welâ€¦
Using examples as well as descriptions, and references to Books Online, show the documentation available for date manipulation functions and by using a select few of these functions, show how date based data can be manipulated with these functions.
Viewers will learn how to use the INSERT statement to insert data into their tables. It will also introduce the NULL statement, to show them what happens when no value is giving for any given column.
###### Suggested Courses
Course of the Month16 days, 7 hours left to enroll