How to replace only the first repeated value in a string in MySQL



For this, you can use REGEXP_REPLACE(). Let’s say our string is βˆ’

This is my first MySQL query. This is the first tutorial. I am learning for the first time.

We need to replace only the 1st occurrence of a specific word, let’s say β€œfirst”. The output should be βˆ’

This is my second MySQL query. This is the first tutorial. I am learning for the first time.

Let us create a table βˆ’

mysql> create table demo26
βˆ’> (
βˆ’> value text
βˆ’> );
Query OK, 0 rows affected (2.04 sec)

Insert some records into the table with the help of insert command βˆ’

mysql> insert into demo26 values('This is my first MySQL query. This is the first tutorial. I am learning for the first time.');
Query OK, 1 row affected (0.10 sec)

Display records from the table using select statement βˆ’

mysql> select *from demo26;

This will produce the following output βˆ’

+---------------------------------------------------------------------------------------------+
| value                                                                                       |
+---------------------------------------------------------------------------------------------+
| This is my first MySQL query. This is the first tutorial. I am learning for the first time. |
+---------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)

Following is the query to replace only 1st occurrence βˆ’

mysql> update demo26
βˆ’> set value = REGEXP_REPLACE(value, 'first', 'second', 1, 1 ) ;
Query OK, 1 row affected (0.19 sec)
Rows matched: 1 Changed: 1 Warnings: 0

Display records from the table using select statement βˆ’

mysql> select *from demo26;

This will produce the following output βˆ’

+----------------------------------------------------------------------------------------------+
| value                                                                                        |
+----------------------------------------------------------------------------------------------+
| This is my second MySQL query. This is the first tutorial. I am learning for the first time. |
+----------------------------------------------------------------------------------------------+
1 row in set (0.00 sec)
Updated on: 2020-11-19T12:17:26+05:30

480 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements