Click here to Skip to main content
15,887,848 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
What is the best way to sort alphanumeric columns? I have mixed type of data in a column such as.
Section
1.0 Project
1.3A
10.0
11
11.1
12.0 Project 2
12.1 A Test
2.0
4.0 A
4.3 B
4.5 C
5.0
5.0 B & M
A1
A10
A11
AB1
AB10
AB100
B1
B2
B20
B21
B3
B32


What I have tried:

I followed an example from Code project but it only had numbers and chars, not mixed. Any help would be greatly appreciated.
Thank you.

How Do I Use SQL Server to Sort Alphanumeric Values?[^]
Posted
Updated 27-Jun-23 22:05pm
Comments
Dave Kreskowiak 23-Jun-23 15:01pm    
Depends on the sorting rules your business rules dictate.
[no name] 23-Jun-23 17:33pm    
Pad the numbers that are less than 10 with a blank or zero on the left.

You can't just try to sort mixed data by "numeric value": string comparisons are always character-by-character, with the first character difference determining the result of the whole comparison - subsequent characters are not even inspected.
So a string comparison of even integer the numbers will not give you teh results you want:
1
10
11
...
19
2
20
21
...


To sort mixed data by numeric values within the string you will have to extract the numeric part, convert it to a number, then sort by that.
And since SQL string manipulation is at best poor, that's going to be a pretty messy job! I'd do it in the presentation language instead as the string manipulation functions are almost certain to be richer!

If you must sort by numeric content in SQL then I'd cheat: add a float column that contains the numeric part as a floating point value so the sort can be done from that and the analysis of the data is only needed on INSERT or UPDATE operations which happen a lot less often than SELECT.

[edit]
Oh, and then I'd use a Regex in the presentation language to extract the numeric value and convert it when I did the INSERT or UPDATE as again, it's probably easier there.
[/edit]
 
Share this answer
 
v2
I assume that what you want is what's called "natural sort".
If you make a search using that criteria you'll find several ready solutions of different quality.

A couple of examples:
SQL Server natural sort function · GitHub[^]
https://stackoverflow.com/questions/34509/natural-human-alpha-numeric-sort-in-microsoft-sql-2005[^]

Neither solution is perfect as they don't seem to support floats, only ints.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900