How to strip all spaces from a column in MySQL?

MySQLMySQLi Database

To strip all spaces from a column in MySQL, you can use REPLACE() function. Following is the syntax −

update yourTableName set yourColumnName=REPLACE(yourColumnName,' ', '' );

Let us first create a table −

mysql> create table stripAllSpacesDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> Name varchar(100)
   -> );
Query OK, 0 rows affected (0.56 sec)

Following is the query to insert records in the table using insert command −

mysql> insert into stripAllSpacesDemo(Name) values('Jo h n');
Query OK, 1 row affected (0.19 sec)
mysql> insert into stripAllSpacesDemo(Name) values(' Joh n');
Query OK, 1 row affected (0.16 sec)
mysql> insert into stripAllSpacesDemo(Name) values('Jo hn');
Query OK, 1 row affected (0.14 sec)
mysql> insert into stripAllSpacesDemo(Name) values('J ohn');
Query OK, 1 row affected (0.17 sec)
mysql> insert into stripAllSpacesDemo(Name) values('John ');
Query OK, 1 row affected (0.14 sec)

Following is the query to display all records from the table using select statement −

mysql> select * from stripAllSpacesDemo;

This will produce the following output −

+----+-----------+
| Id | Name      |
+----+-----------+
| 1  | Jo h n    |
| 2  | Joh n     |
| 3  | Jo hn     |
| 4  | J ohn     |
| 5  | John      |
+----+-----------+
5 rows in set (0.00 sec)

Here is the query to strip all spaces from column in MySQL −

mysql> update stripAllSpacesDemo set Name=REPLACE(Name,' ','');
Query OK, 5 rows affected (0.12 sec)
Rows matched: 5 Changed: 5 Warnings: 0

Let us display all records from the table once again to check all spaces have been stripped or not −

mysql> select * from stripAllSpacesDemo;

This will produce the following output −

+----+------+
| Id | Name |
+----+------+
| 1  | John |
| 2  | John |
| 3  | John |
| 4  | John |
| 5  | John |
+----+------+
5 rows in set (0.00 sec)
raja
Published on 16-Apr-2019 13:09:55
Advertisements