Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to order by largest number

Tags:

mysql

I've got a pretty simple question, I think..

I've got a database field that stores the byte size of files. I want to order by the largest file_size, but it's not working as I'd hoped...

I've tried

SELECT * 
FROM file_data
ORDER BY file_size DESC

and

SELECT * 
FROM file_data
ORDER BY MAX( file_size ) DESC

Thanks.

EDIT:

The reason it's not working as expected is because these are the results from the first query:

ID    file_size
13    980616    
200    9782897  
199    9732752  
187    967006   
166    9614688  
12    9481028   
44    945120    
65    9228440   
208    92140357
like image 509
i-CONICA Avatar asked Jan 17 '23 18:01

i-CONICA


1 Answers

if file_size is a CHAR/VARCHAR field probably the result is not what you expected (edit: in support of my thesis, the resultset you posted seems to be alphabetically sorted)

So try to change the column data type to INTEGER or, if you cannot alter the table, make an explicit casting in your query using

SELECT * 
FROM file_data
ORDER BY CAST(file_size AS INTEGER) DESC

see http://dev.mysql.com/doc/refman/5.0/en/cast-functions.html

like image 191
Fabrizio Calderan Avatar answered Jan 25 '23 22:01

Fabrizio Calderan