Sort VARCHAR as INT in MySQL
13
Jun1
Jun1
Sometimes we can user VARCHAR for integer values. But when we need sort them, we have got big problem. Because VARCHAR’s are string and it is sorting like a string.
Example:
1a 2a 3a 10b 20b 30b 15c 25c 35c (VARCHAR)
1a 10b 15c 2a 20b 25c 3a 30b 35c (Sorted)
We need
1a 2a 3a 10b 15c 20b 25c 30b 35c (Sorted integer)
We can do it with mysql CAST
SELECT vNumber FROM table ORDER BY CAST(`vNumber` AS SIGNED)
Reverse orderSELECT vNumber FROM table ORDER BY CAST(`vNumber` AS SIGNED) DESCOther possible conversion types you may need are:
- BINARY[(N)]
- CHAR[(N)]
- DATE
- DATETIME
- DECIMAL[(M[,D])]
- SIGNED [INTEGER]
- TIME
- UNSIGNED [INTEGER]
1 Comment
Sorry, the comment form is closed at this time.


19:51 on October 12th, 2011
thanks..