MySQL search and replace record from a list of records


Let us first create a table −

mysql> create table DemoTable
   -> (
   -> ListOfName text
   -> );
Query OK, 0 rows affected (0.66 sec)

Insert some records in the table using insert command −

mysql> insert into DemoTable values('Carol,Sam,John,David,Bob,Mike,Robert,John,Chris,James,Jace');
Query OK, 1 row affected (0.13 sec)

Display all records from the table using select statement −

mysql> select *from DemoTable;

This will produce the following output −

+------------------------------------------------------------+
| ListOfName                                                 |
+------------------------------------------------------------+
| Carol,Sam,John,David,Bob,Mike,Robert,John,Chris,James,Jace |
+------------------------------------------------------------+
1 row in set (0.00 sec)

Here is the query to search and replace a record from a list of records−

mysql> update DemoTable
   -> set ListOfName=
   -> concat(substring_index(ListOfName,'John',2) ,'Adam', SUBSTRING_INDEX(ListOfName, 'John', -1));
Query OK, 1 row affected (0.37 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again −

mysql> select *from DemoTable;

This will produce the following output −

+------------------------------------------------------------+
| ListOfName                                                 |
+------------------------------------------------------------+
| Carol,Sam,John,David,Bob,Mike,Robert,Adam,Chris,James,Jace |
+------------------------------------------------------------+
1 row in set (0.00 sec)

Updated on: 13-Dec-2019

99 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements