How to find and replace string in MySQL database for a particular string only?

MySQLMySQLi Database

Use the replace() function to replace string in MySQL Database.

The syntax is as follows

UPDATE yourTableName
SET yourColumnName=replace(yourColumnName,'yourExistingValue','yourNewValue')
WHERE <yourCondition>>;

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

mysql> create table findAndReplaceDemo
   -> (
   -> Id int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> StudentFirstName varchar(20)
   -> );
Query OK, 0 rows affected (0.49 sec)

Insert some records in the table using insert command.

The query is as follows

mysql> insert into findAndReplaceDemo(StudentFirstName) values('Carol');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('David');
Query OK, 1 row affected (0.15 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Bob');
Query OK, 1 row affected (0.10 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Sam');
Query OK, 1 row affected (0.11 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Mike');
Query OK, 1 row affected (0.13 sec)
mysql> insert into findAndReplaceDemo(StudentFirstName) values('Maxwell');
Query OK, 1 row affected (0.17 sec)

Display all records from the table using select statement.

The query is as follows

mysql> select *from findAndReplaceDemo;

The following is the output

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Maxwell          |
+----+------------------+
6 rows in set (0.00 sec)

Here is the query to find and replace string in MySQL database for a particular string only

mysql> update findAndReplaceDemo
   -> set StudentFirstName=replace(StudentFirstName,'Maxwell','Chris')
   -> where StudentFirstName='Maxwell';
Query OK, 1 row affected (0.16 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Let us check the table records once again, the value 'Maxwell’ have been changed to ‘Chris.

The query is as follows

mysql> select *from findAndReplaceDemo;

The following is the output with updated value

+----+------------------+
| Id | StudentFirstName |
+----+------------------+
| 1  | Carol            |
| 2  | David            |
| 3  | Bob              |
| 4  | Sam              |
| 5  | Mike             |
| 6  | Chris            |
+----+------------------+
6 rows in set (0.00 sec)
raja
Published on 29-Mar-2019 07:03:37
Advertisements