How to cast and update a numeric value from string column only where applicable in MySQL?



You can use the CEIL() function from MySQL. Let us first create a table. Here, we have taken the first column as VARCHAR −

mysql> create table DemoTable    -> (    -> Value varchar(20),    -> UpdateValue int    -> ); Query OK, 0 rows affected (1.08 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable(Value) values('100'); Query OK, 1 row affected (0.11 sec) mysql> insert into DemoTable(Value) values('false'); Query OK, 1 row affected (0.10 sec) mysql> insert into DemoTable(Value) values('true'); Query OK, 1 row affected (0.07 sec) mysql> insert into DemoTable(Value) values('1'); Query OK, 1 row affected (0.07 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------------+ | Value | UpdateValue | +-------+-------------+ |   100 |        NULL | | false |        NULL | |  true |        NULL | |     1 |        NULL | +-------+-------------+ 4 rows in set (0.00 sec)

Following is the query to cast and update a numeric value from string column only where applicable −

mysql> update DemoTable    -> set UpdateValue=ceil(cast(Value AS char(7))); Query OK, 4 rows affected (0.18 sec) Rows matched: 4 Changed: 4 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+-------+-------------+ | Value | UpdateValue | +-------+-------------+ |   100 |         100 | | false |           0 | |  true |           0 | |     1 |           1 | +-------+-------------+ 4 rows in set (0.00 sec)
Updated on: 2019-12-12T05:59:36+05:30

548 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements