How to cast from VARCHAR to INT in MySQL?

MySQLMySQLi Database

To cast VARCHAR to INT, we can use the cast() function from MySQL. Here is the syntax of cast() function.

cast(anyValue as dataType)

For our example, we will create a table with the help of create command.

mysql> create table VarchartointDemo
   -> (
   -> Value varchar(100)
   -> );
Query OK, 0 rows affected (0.51 sec)

After creating a table, let us insert some records into the table with the help of INSERT command. The query is as follows −

mysql> insert into VarchartointDemo values('123');
Query OK, 1 row affected (0.26 sec)

mysql> insert into VarchartointDemo values('234');
Query OK, 1 row affected (0.16 sec)

Display all records with the help of select statement.

mysql> select *from VarchartointDemo;

The following is the output.

+-------+
| Value |
+-------+
| 123   |
| 234   |
+-------+
2 rows in set (0.00 sec)

Cast varchar to int using the following syntax.

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.

+-------------------------+
| CAST(Value AS UNSIGNED) |
+-------------------------+
|                     123 |
|                     234 |
+-------------------------+
2 rows in set (0.00 sec)

Look at the above output, we have changed varchar to int.

raja
Published on 29-Nov-2018 17:39:12
Advertisements