Update existing column data in MySQL and remove the last string from a varchar column with strings and numbers

MySQLMySQLi Database

Let us first create a table −

mysql> create table DemoTable
(
   Download varchar(100)
);
Query OK, 0 rows affected (0.53 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('120 Gigabytes');
Query OK, 1 row affected (0.17 sec)
mysql> insert into DemoTable values('190 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('250 Gigabytes');
Query OK, 1 row affected (0.14 sec)
mysql> insert into DemoTable values('1000 Gigabytes');
Query OK, 1 row affected (0.12 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+----------------+
| Download       |
+----------------+
| 120 Gigabytes  |
| 190 Gigabytes  |
| 250 Gigabytes  |
| 1000 Gigabytes |
+----------------+
4 rows in set (0.00 sec)

Following is the query to update existing column data and remove the last string −

mysql> update DemoTable set Download=LEFT(Download, INSTR(Download, ' ') - 1);
Query OK, 4 rows affected (0.16 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 −

+----------+
| Download |
+----------+
| 120      |
| 190      |
| 250      |
| 1000     |
+----------+
4 rows in set (0.00 sec)
raja
Published on 25-Sep-2019 15:54:45
Advertisements