MySQL find/ replace string in fields?


To find/replace string in fields, the syntax is as follows −

update yourTableName
set yourColumnName =REPLACE(yourColumnName,yourOldValue,yourNewValue);

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

mysql> create table FindReplaceDemo
   -> (
   -> FileId int NOT NULL AUTO_INCREMENT PRIMARY KEY,
   -> FileDirectory text
   -> );
Query OK, 0 rows affected (0.92 sec)

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

mysql> insert into FindReplaceDemo(FileDirectory) values('C://User//MySQL');
Query OK, 1 row affected (0.19 sec)
mysql> insert into FindReplaceDemo(FileDirectory) values('D://WebsiteImage//image1.jpg');
Query OK, 1 row affected (0.12 sec)
mysql> insert into FindReplaceDemo(FileDirectory) values('E://Java//AdvancedJava');
Query OK, 1 row affected (0.20 sec)

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

mysql> select *from FindReplaceDemo;

Here is the output −

+--------+------------------------------+
| FileId | FileDirectory                |
+--------+------------------------------+
| 1      | C://User//MySQL              |
| 2      | D://WebsiteImage//image1.jpg |
| 3      | E://Java//AdvancedJava       |
+--------+------------------------------+
3 rows in set (0.00 sec)

Here is the query to find/replace string in fields −

mysql> update FindReplaceDemo
   -> set FileDirectory =REPLACE(FileDirectory,'E://Java//AdvancedJava','E://Java//SpringAndHibernateFramework');
Query OK, 1 row affected (0.12 sec)
Rows matched: 3 Changed: 1 Warnings: 0

Now let us check the table records once again. The query is as follows −

mysql> select *from FindReplaceDemo;

The output is as follows with replaced values −

+--------+---------------------------------------+
| FileId | FileDirectory                         |
+--------+---------------------------------------+
| 1      | C://User//MySQL                       |
| 2      | D://WebsiteImage//image1.jpg          |
| 3      | E://Java//SpringAndHibernateFramework |
+--------+---------------------------------------+
3 rows in set (0.00 sec)

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 30-Jul-2019

231 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements