SELECT `01` FROM perf WHERE year = '2013' order by CAST(`01` AS INT) LIMIT 3
Column 01 has numeric values as varchar. I need to order top 3 of ’01’ as integer. Why doesn’t this query working?
Table like this;
+----------------------+
| name | 01 | 02 | year|
+----------------------+
|name1 | 90 |*** |2013 |
+----------------------+
|name2 | 93 | 55 |2013 |
+----------------------+
|name3 |*** | 78 |2013 |
+----------------------+
Query should order by 01 (dismiss *) and give names and values.
MySQL doesn’t permit you to
CAST('01' AS INT). It expects instead aSIGNEDorUNSIGNED.Review the MySQL docs on
CAST()for full details.To force the non-numeric strings to be sorted last, you will need to apply a
CASEin theORDER BYwhich assigns them an absurdly high value. The condition should test that the value in01is not equal to0, and when cast to aSIGNEDthe result is not0, owing to the fact that non-numeric strings will cast to zero.If those conditions are not met, the string is assumed to be non-numeric, and given a value of 999999999 in the
ORDER BY, which pushes them to the end. They’re subsequently ordered byname.http://sqlfiddle.com/#!2/846e2/6
To make these sort descending, use an absurdly low value (negative) instead of a high value