how to sort varchar numeric columns by DESC or ASC?

Henrikh picture Henrikh · Oct 16, 2011 · Viewed 16.2k times · Source

I write ...

ORDER BY column ASC

but my column is VARCHAR and it sorts wrong like 1, 10, 2, instead of 1, 2, 10.

How can I do it to sort like 1, 2, 10?

Answer

gbn picture gbn · Oct 16, 2011
order by 
   cast(column as float)

Notes:

  • Assumed you only have numbers in the columns. No "fish" or "bicycle"
  • empty strings CAST to zero

Edit: For MySQL. You can not cast to float

order by 
   cast(column as decimal(38,10))