Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL, varchar field with decimals entries = ORDER BY not sorting proprely

So i have a table with a VARCHAR field. It is used to sort a lot of decimals value:

Let's say i have the following entries in my VARCHAR field:

  • 9.99
  • 263.28
  • 9.98

Let's say I want to display all entries using ORDER BY varchar DESC. The result would be:

  • 9.99
  • 9.98
  • 263.28

When obviously 263.28 should be the first one. What's wrong ?

like image 706
libertaire Avatar asked Jan 30 '26 11:01

libertaire


1 Answers

If you have all decimal values in varchar field then just convert it to decimal and then apply order by clause. I have not much idea about mysql data type and convert function, but in MS SQL you can convert it to decimal like

ORDER BY CAST(field AS DECIMAL(18,2)) DESC

UPDATE :

Yes, in MySQL also there is cast function : http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

like image 50
Upendra Chaudhari Avatar answered Feb 01 '26 00:02

Upendra Chaudhari



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!