MySQL Query to remove all characters after last comma in string?


To remove all characters after the last comma in the string, you can use SUBSTRING_INDEX().

If you do not know the location of the last comma, then you need to find the last comma dynamically using LENGTH().

The syntax is as follows −

UPDATE yourTableName
set yourColumnName = SUBSTRING_INDEX(yourColumnName, ',',
LENGTH(yourColumnName) - LENGTH(REPLACE(yourColumnName, ',', '')));

To understand the above syntax, let us create a table. The query to create a table is as follows −

mysql> create table RemoveAllCharacters
   -> (
   -> Id int NOT NULL AUTO_INCREMENT,
   -> FullInfo varchar(200),
   -> PRIMARY KEY(Id)
   -> );
Query OK, 0 rows affected (1.83 sec)

Insert some records in the table using insert command. The query is as follows −

mysql> insert into RemoveAllCharacters(FullInfo) values('John,Smith,23,98,4565886');
Query OK, 1 row affected (0.23 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('Carol,Taylor,26,91');
Query OK, 1 row affected (0.28 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('David,Miller,21');
Query OK, 1 row affected (0.11 sec)

mysql> insert into RemoveAllCharacters(FullInfo) values('Robert,Jones,22,97');
Query OK, 1 row affected (0.09 sec)

mysql> insert into RemoveAllCharacters(FullInfo)
values('Sam,Williams,27,88,456788,97877');
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 RemoveAllCharacters;

The following is the output −

+----+---------------------------------+
| Id | FullInfo                        |
+----+---------------------------------+
| 1  | John,Smith,23,98,4565886        |
| 2  | Carol,Taylor,26,91              |  
| 3  | David,Miller,21                 |
| 4  | Robert,Jones,22,97              |
| 5  | Sam,Williams,27,88,456788,97877 |
+----+---------------------------------+
5 rows in set (0.00 sec)

The following is the query to remove all characters after last comma in string −

mysql> update RemoveAllCharacters
   -> set FullInfo = SUBSTRING_INDEX(FullInfo, ',', LENGTH(FullInfo) - LENGTH(REPLACE(FullInfo, ',', '')));
Query OK, 5 rows affected (0.28 sec)
Rows matched: 5 Changed: 5 Warnings: 0

Now check all the records of table once again. The query is as follows −

mysql> select *from RemoveAllCharacters;

The following is the output displaying the records without the characters after the last comma:

+----+---------------------------+
| Id | FullInfo                  |
+----+---------------------------+
|  1 | John,Smith,23,98          |
|  2 | Carol,Taylor,26           |
|  3 | David,Miller              |
|  4 | Robert,Jones,22           |
|  5 | Sam,Williams,27,88,456788 |
+----+---------------------------+
5 rows in set (0.00 sec)

Updated on: 30-Jun-2020

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements