I have a varchar field in my table and I want to sort it. But I need to handle this field as integer. Meaning if sort as text the order is "19,2,20" but I want to get the right order "2,19,20".
Can anyone help me?
SELECT * FROM mytable ORDER BY CAST(mycol AS DECIMAL) @dnagirl: DECIMAL will silently truncate everything beyond the [0-9] range, mycol + 0 (which implies CAST AS DOUBLE) will issue a warning. As for performance, I think they're identical.All other answers use ABS, which converts the values into absolute (positive) values, assuming that the integers are positive. A better solution would be to use * 1:
SELECT * FROM mytable ORDER BY mycol * 1
This to prevent casting negative numbers into positive ones. Inspired by: mysql sort string number