Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting varchar to int in mysql

Tags:

mysql

I have a column airline_id which is varchar in the table route, now I want to copy that value into the column airline_id_int which has the type int. I can't get the syntax right though..

This is what I have:

UPDATE route SET airline_id_int = CAST(airline_id, int);
like image 872
user1907859 Avatar asked Oct 31 '13 09:10

user1907859


People also ask

How do I convert varchar to int in MySQL?

SELECT CAST(yourColumnName AS anyDataType) FROM yourTableName; Apply the above syntax to cast varchar to int. mysql> SELECT CAST(Value AS UNSIGNED) FROM VarchartointDemo; The following is the output.

How do I CAST datatype in MySQL?

The CAST() function in MySQL is used to convert a value from one data type to another data type specified in the expression. It is mostly used with WHERE, HAVING, and JOIN clauses. This function is similar to the CONVERT() function in MySQL. It converts the value into DATE datatype in the "YYYY-MM-DD" format.

Can you convert varchar to numeric in SQL?

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.


3 Answers

You have to use the AS keyword for CAST.

update route set airline_id_int = cast(airline_id AS UNSIGNED)

You can use

update route set airline_id_int = cast(airline_id AS SIGNED)

as well.

like image 128
MusicLovingIndianGirl Avatar answered Oct 17 '22 08:10

MusicLovingIndianGirl


Try the following:

update route set airline_id_int = cast(airline_id AS UNSIGNED);

It's not possible to cast directly to int. If you need signed int, replace UNSIGNED with SIGNED.

like image 32
Obl Tobl Avatar answered Oct 17 '22 09:10

Obl Tobl


update route set airline_id_int = cast(airline_id as signed);

or

update route set airline_id_int = cast(airline_id as unsigned);

if it can be negative

like image 45
Frederic Close Avatar answered Oct 17 '22 09:10

Frederic Close