Pages

Tuesday, November 29, 2011

Sorting strings and numbers(varchar type column) in SQL query

Problem :
                  I have a problem with sorting by a string-column when i use SQL query on MySQLServer. There are both numbers, strings and mixture of both in this column and when i sort it numbers are not looks in sorting. ex. 7.5 6 14 8.5 9. I would like to sort numbers numerically and both strings and mixed alphabetically, 14 6 7.5 8.5 9.


Soluation :

Set your query in sorting by using "order by '0000000000'+rtrim(FEILDNAME)" 

Where FEILDNAME is your varchar type column name which you want to sort. This will build up a string for the numbers with leading zeros, so they will get sorted correctly.