I want to sort the following data items in the order they are presented below (numbers 1-12):
1 2 3 4 5 6 7 8 9 10 11 12
However, my query - using order by xxxxx asc
sorts by the first digit above all else:
1 10 11 12 2 3 4 5 6 7 8 9
Any tricks to make it sort more properly?
Further, in the interest of full disclosure, this could be a mix of letters and numbers (although right now it is not), e.g.:
A1 534G G46A 100B 100A 100JE
etc....
Thanks!
update: people asking for query
select * from table order by name asc
Instead of trying to write some function and slow down the
SELECT
query, I thought of another way of doing this...Create an extra field in your database that holds the result from the following Class and when you insert a new row, run the field value that will be naturally sorted through this class and save its result in the extra field. Then instead of sorting by your original field, sort by the extra field.
String nsFieldVal = new NaturalSortString(getFieldValue(), 4).toString()
String sortString = new NaturalSortString(getString(), 4).toString()
For completeness, below is the
StringUtils.padLeft
method:The result should come out like the following
This works for type of data: Data1, Data2, Data3 ......,Data21. Means "Data" String is common in all rows.
For ORDER BY ASC it will sort perfectly, For ORDER BY DESC not suitable.
If you need to sort an alpha-numeric column that does not have any standard format whatsoever
You can adapt this solutation to include support for non-alphanumeric characters if desired using additional logic.
I know this post is closed but I think my way could help some people. So there it is :
My dataset is very similar but is a bit more complex. It has numbers, alphanumeric data :
I would like to have the '-' symbol at first, then the numbers, then the text.
So I go like this :
The result should be something :
The whole idea is doing some simple check into the SELECT and sorting with the result.
I hate this, but this will work
This should sort alphanumeric field like: 1/ Number only,
order by 1,2,3,4,5,6,7,8,9,10,11
etc... 2/ Then field with text like:1foo, 2bar, aaa11aa, aaa22aa, b5452
etc...The query check if the data is a number, if not put it to 9999999999 , then order first on this column, then order on data with text
Good luck!