Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

mysql order varchar field as integer

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?

like image 909
ntan Avatar asked Oct 26 '09 14:10

ntan


People also ask

How can I order varchar number?

'LPAD(lower(column_name))' is used to sort the varchar field numerically in MySQL.

Can varchar have integers?

VARCHAR (length) The VARCHAR data type accepts character strings, including Unicode, of a variable length is up to the maximum length specified in the data type declaration. A VARCHAR declaration must include a positive integer in parentheses to define the maximum allowable character string length.


1 Answers

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.

like image 110
yentsun Avatar answered Oct 06 '22 00:10

yentsun