Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mysql ORDER BY numbers DESC

I have a simple mysql select query in my PHP code:

$result = mysql_query("SELECT text FROM example ORDER BY rank DESC");
while($row = mysql_fetch_array($result))
  {
  echo $row['text'] . "<br>";
  }

and this MySql table:

   text | rank
--------+--------
 google | 245
--------+--------
 yahoo  | 32
--------+--------
 bing   | 12

When I get the results from the query, something like this gets displayed:

yahoo 
google
bing

I want Google to be in front. I guess Yahoo is in first because it starts with "3".

How could I make the query order the results by the size of the numbers in rank?

Thanks...

like image 583
Akos Avatar asked Nov 30 '22 15:11

Akos


2 Answers

I'm guessing the rank field is some kind of string type. Make it a numeric type int and it will order properly

like image 72
Nick Rolando Avatar answered Dec 04 '22 08:12

Nick Rolando


The correct solution, of course, is to use the correct data type. As a workaround you could cast the data to number on the fly:

SELECT text FROM example ORDER BY rank + 0 DESC

or:

SELECT text FROM example ORDER BY cast(rank as unsigned) DESC
like image 37
Dimitre Radoulov Avatar answered Dec 04 '22 09:12

Dimitre Radoulov