tags:

views:

88

answers:

3

I have 2 products, one is a thousand dollars so for it's price I inserted into the database:

1000.00

and nother thats 34 dollars so I inserted:

34.00

But when I sort the products in order by price (low to high) the $1,000 product comes before the $34 one, why?

The query:

SELECT * FROM products ORDER BY price ASC;

EDIT

It's a varchar field. I would have used int but I need the decimal to be accepted.

If I turn it to int, is there any way I can convert something like this:

10000

to a more user friendly form when display to the user like:

$10,000

I am using PHP for scripting by the way.

+4  A: 

Because strings are sorted lexicographically. You need to cast it to a number to be sorted numerically.

SELECT * FROM products ORDER BY CAST(price AS DECIMAL) ASC;

(It may be better to store the price as INTEGERs as multiple of cents (100000 and 3400), or use DECIMAL.)


Edit: You can use money_format in PHP to convert a number to currency format. See http://www.ideone.com/VEcgy for an example.

KennyTM
that is a pretty nice question inst double more applicable for currency ?
Prix
@Prix: [ __No__ !](http://stackoverflow.com/questions/61872/use-float-or-decimal-for-accounting-application-dollar-amount/66678#66678)
KennyTM
thanks, that is pretty interesting :)
Prix
+3  A: 

Lexically speaking, 1000.00 is less than 34.00. What data type is price?

Chris
A: 

You've stored price as an varchar, but indeed it is numeric ;)
Use DECIMAL(10,2) or DOUBLE(10,2) to store the price, both types preserve the point.

Tobias P.
I actually prefer DECIMAL(10,4) as people like the IRS can specify sub 1 cent values (such as car mileage rebate rates)
Peter M