Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Varchar to number conversion for sorting

I have a query ordered by column:

select * from mytable order by column asc — sort table 

column type is varchar, so the output is:

1 10 100 11 12 13 

How should I sort if I want them to sort by numeric value so the output is:

1 10 11 12 13 100 
like image 643
Dmitry Avatar asked Dec 08 '09 18:12

Dmitry


People also ask

How do I convert varchar to numeric?

To convert a varchar type to a numeric type, change the target type as numeric or BIGNUMERIC as shown in the example below: SELECT CAST('344' AS NUMERIC) AS NUMERIC; SELECT CAST('344' AS BIGNUMERIC) AS big_numeric; The queries above should return the specified value converted to numeric and big numeric.

Can I use varchar for numbers?

As the name suggests, varchar means character data that is varying. Also known as Variable Character, it is an indeterminate length string data type. It can hold numbers, letters and special characters.


1 Answers

Use:

order by cast(column as unsigned) asc 
like image 99
Pablo Santa Cruz Avatar answered Oct 06 '22 00:10

Pablo Santa Cruz