Update all rows in MySQL and remove all the unnecessary whitespaces in and around the string?

MySQLMySQLi Database

To remove unnecessary whitespaces, use TRIM() in MySQL. Let us first create a −

mysql> create table DemoTable1405
   -> (
   -> FirstName varchar(20),
   -> LastName varchar(20)
   -> );
Query OK, 0 rows affected (0.55 sec)

Insert some records in the table using insert −

mysql> insert into DemoTable1405 values('   Chris',' Brown ');
Query OK, 1 row affected (0.20 sec)
mysql> insert into DemoTable1405 values('David      ',' Miller ');
Query OK, 1 row affected (0.24 sec)
mysql> insert into DemoTable1405 values('     Carol ',' Taylor ');
Query OK, 1 row affected (0.19 sec)

Display all records from the table using select −

mysql> select * from DemoTable1405;

This will produce the following output −

+------------------+----------------+
| FirstName        | LastName       |
+------------------+----------------+
|    Chris         |    Brown       |
| David            |    Miller      |
|      Carol       |    Taylor      |
+------------------+----------------+
3 rows in set (0.00 sec)

Following is the query to remove all the unnecessary whitespaces and update all rows −

mysql> update DemoTable1405 set FirstName=trim(FirstName),LastName=trim(LastName);
Query OK, 3 rows affected (0.18 sec)
Rows matched: 3  Changed: 3 Warnings: 0

Let us check the table records once again −

mysql> select * from DemoTable1405;

This will produce the following output −

+-----------+----------+
| FirstName | LastName |
+-----------+----------+
| Chris     | Brown    |
| David     | Miller   |
| Carol     | Taylor   |
+-----------+----------+
3 rows in set (0.00 sec)
raja
Published on 11-Nov-2019 11:00:13
Advertisements