How to trim commas with MySQL?

MySQLMySQLi Database

The syntax is as follows to trim commas −

SELECT TRIM(BOTH ',' FROM yourColumnName) from yourTableName;

Let us see an example −

mysql> create table TrimCommasDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> AllTechnicalSkills text
   -> );
Query OK, 0 rows affected (0.81 sec)

Now you can insert some records in the table using insert command. The query is as follows −

mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',C,C++,Java,');
Query OK, 1 row affected (0.14 sec)
mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',MySQL,SQL
Server,MongoDB,');
Query OK, 1 row affected (0.13 sec)
mysql> insert into TrimCommasDemo(AllTechnicalSkills) values(',Spring
Framework,Hibernate Framework,');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement. The query is as follows −

mysql> select *from TrimCommasDemo;

Here is the output −

+----+----------------------------------------+
| Id | AllTechnicalSkills                     |
+----+----------------------------------------+
| 1  | ,C,C++,Java,                           |
| 2  | ,MySQL,SQL Server,MongoDB,             |
| 3  | ,Spring Framework,Hibernate Framework, |
+----+----------------------------------------+
3 rows in set (0.00 sec)

The following is the query to trim commas from leading and trailing with MySQL −

mysql> select TRIM(BOTH ',' FROM AllTechnicalSkills) from TrimCommasDemo;

Here is the output −

+----------------------------------------+
| TRIM(BOTH ',' FROM AllTechnicalSkills) |
+----------------------------------------+
| C,C++,Java                             |
| MySQL,SQL Server,MongoDB               |
| Spring Framework,Hibernate Framework   |
+----------------------------------------+
3 rows in set (0.00 sec)
raja
Published on 01-Apr-2019 06:51:24
Advertisements