mysql order varchar field as integer

旧城冷巷雨未停 提交于 2019-12-02 21:51:46

I somehow didn't manage to run the query with CAST. I was always getting Error Code: 1064 near "DECIMAL" (or other numeric type that I chose). So, I found another way to sort varchar as numbers:

SELECT *
FROM mytable
ORDER BY ABS(mycol)

A bit simpler and works in my case.

SELECT  *
FROM    mytable
ORDER BY
        CAST(mycol AS DECIMAL)

Here is the solution

SELECT * FROM MyTable ORDER BY ABS(MyCol);
Guido

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

You can ABS() for this purpose. ABS() is a mathematical function that returns the absolute (positive) value of the specified expression. So query will be something like this

SELECT * FROM MyTable ORDER BY ABS(MyCol);

You Can Order varchar field using this code according to your required

SELECT * FROM mytable ORDER BY ABS(mycol)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!