Henrikh Henrikh - 2 months ago 10
MySQL Question

how to sort varchar numeric columns by DESC or ASC?

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
?

gbn gbn
Answer
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))