Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ordering varchar field with decimals numbers and none decimal numbers

Tags:

php

mysql

Varchar field with decimals numbers and none decimal numbers.

Ex:

100.02
99
9
200.56
500.4
10.1
6

How do i order it to display in ASC order

I tried below codes with no luck

SELECT * FROM posts ORDER BY CAST(price AS DECIMAL(10,2)) DESC LIMIT 0, 9

Also

SELECT * FROM posts ORDER BY convert(price, decimal) DESC LIMIT 0, 9

But none of the above codes seems to work. Can someone point me out the proper way to do this.

like image 633
max Avatar asked Nov 25 '25 13:11

max


1 Answers

The sorting issue is due to the use of a sting type field for a number, it will never sort as a human would expect.

if the field type is price, you should never use float, instead you should use DECIMAL or NUMERIC

The DECIMAL and NUMERIC types store exact numeric data values. These types are used when it is important to preserve exact precision, for example with monetary data.

you don't want an "approximate" value for a price

The FLOAT and DOUBLE types represent approximate numeric data value


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!