5

I have this sql query

SELECT `price` FROM `used_cars` ORDER BY `price` DESC 

So I obviously want to order by price from high to low. However, it seems to be taking the first digit and sorting by that. My theory is that it is treating it like a string, and as the column is a varchar it makes sense. However, this is third party data, so I am stuck with it. How can I order so that the larger numbers come first?

So this is an example of how they are ordered

9698
8999
8988
8900
5983
4988
4984
42441
40949
3995
3995
38995
37685
36999
35983
34990
34785
32999
30594
29999
29999
2862
28000
27995
user2909486
  • 547
  • 4
  • 8
  • 17
  • 3
    See http://stackoverflow.com/questions/12126991/cast-from-varchar-to-int-mysql for how to cast to an int – Palpatim May 01 '14 at 22:59
  • 1
    This is expected behavior for a text column that should be a decimal. To change it, first back up your database, then run the following command: ALTER TABLE user_cars MODIFY COLUMN price DECIMAL(10,2); – Tim Burch May 01 '14 at 23:01
  • @TimBurch is right - you need to change the type of your data. You say that this is third-party data, but it's obviously in _your_ database... are you just uploading data from a third-party file? Nothing's preventing you from loading to a temp-file first, then casting when going to the final destination. Numeric data should be stored in a numeric column. – Clockwork-Muse May 02 '14 at 00:08

4 Answers4

11

You should convert the column to a numeric data type. You can do that in the table definition, or in the query itself, for example with:

... ORDER BY `price`+0 DESC
Joni
  • 108,737
  • 14
  • 143
  • 193
6

CAST should work:

SELECT CAST(price AS UNSIGNED) AS NumPrice
FROM used_cars
ORDER BY NumPrice DESC
Dave Jemison
  • 694
  • 3
  • 7
2

This should work:

(...)
ORDER BY CAST (price AS INT)
wvdz
  • 16,251
  • 4
  • 53
  • 90
  • Rather than resort to casting, which is inefficient, the type of the column should be changed to decimal. – Tim Burch May 01 '14 at 23:04
-1

This will work but is bad performance

SELECT price FROM used_cars ORDER BY CAST(price AS int) DESC
zoruc
  • 819
  • 7
  • 13