Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order by numeric values in SQL ascending

I'm trying to get this output.

MDT 1
MDT 2
MDT 3
MDT 11
MDT 44

but, The values are ordered alphabetically, so 123 comes before 2.

example :

MDT 1
MDT 11
MDT 156
MDT 2
MDT 3
MDT 303
MDT 44

and so on.

I'm use this code, but it seem didn't work.

SELECT * FROM file ORDER BY ABS(ID) ASC

How can I solve this?

like image 517
melati Avatar asked Dec 04 '12 04:12

melati


2 Answers

If your ID is always going to contain the prefix as MDT, then you can use this, to sort as per your requirement:

SELECT * FROM File 
ORDER BY CAST(replace(ID, 'MDT ', '') AS UNSIGNED) ASC

SQLFiddle demo

like image 115
Vikdor Avatar answered Sep 21 '22 03:09

Vikdor


Try that snippet

SELECT * FROM file ORDER BY ID + 0 ASC
like image 43
Jonathan de M. Avatar answered Sep 24 '22 03:09

Jonathan de M.