views:

52

answers:

2

How do you order by number if your number can fall below and be bigger than 0?

Example Mysql table:

|Name|Karma|
 __________
|Me  | -8  |
|Bill|  5  |
|Tom |  2  |
|Saly|  0  |
|San.| -3  |

Example select query

$sql="SELECT karma FROM table ORDER BY karma DESC";

The result I get is this (separated by comma): 5,2,0,-8,-3. Shouldn't it be 5,2,0,-3,-8? I discovered somewhere in the internet that mysql orders by string. How to make it order by number?

+9  A: 

Karma will be ordered as a string if you have made it a string, i.e. a varchar column.

Convert the column to a INT, and it will order numerically.

You also have the option of not changing the table, but casting the column into the right type while sorting:

SELECT karma FROM table ORDER BY CAST(karma AS int) DESC

but that is bad for performance.

Pekka
Hm, I thought varchar will do the trick, BUT I was wrong. Thanks!
ne5tebiu
The correct way is to store this value is an INT, not a VARCHAR, used a signed value, that way you can do negatives. It'll improve your performance plus you can add|substract to the column without your PHP code knowing the value, which is another performance improvement.
TravisO
+2  A: 

There's another weirdest option:

SELECT karma FROM table ORDER BY karma+0 DESC
Cristian
Nice! Didn't know mySQL did that. Still, it's an implicit cast and not good for performance.
Pekka
Isn't this solution hackable?
ne5tebiu
@ne5tebio Hackable? You mean from outside? I don't think so. How would that work?
Pekka
Well if someone would inject a script that changes all 0 to something else, that would be a burden...
ne5tebiu