Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql select order by acts like a string, not a number

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?

like image 325
Aistis Avatar asked Jul 01 '10 19:07

Aistis


People also ask

How do I sort a varchar column in MySQL?

'LPAD(lower(column_name))' is used to sort the varchar field numerically in MySQL.

How do I sort numbers in MySQL?

The ORDER BY keyword is used to sort the result-set in ascending or descending order. The ORDER BY keyword sorts the records in ascending order by default. To sort the records in descending order, use the DESC keyword.

How do I select only the value of an integer in MySQL?

Syntax to check if the value is an integer. select yourColumnName from yourTableName where yourColumnName REGEXP '^-?[0-9]+$'; The query wherein we have used regular expression. This will output only the integer value.


2 Answers

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.

like image 84
Pekka Avatar answered Oct 07 '22 15:10

Pekka


There's another weirdest option:

SELECT karma FROM table ORDER BY karma+0 DESC
like image 26
Cristian Avatar answered Oct 07 '22 15:10

Cristian