Perform search/replace for only the first occurrence of a character with session variable in MySQL


To perform search/ replace for only the first occurrence, use the CONCAT and REPLACE() function.

The query is as follows to set user defined session variable −

mysql> set @Sentence='Thks ks is a my string';
Query OK, 0 rows affected (0.00 sec)

In this k will be replaced with i only once. The query is as follows. We have used INSTR() also −

mysql> select @Sentence as NewString ,CONCAT(REPLACE(LEFT(@Sentence,
INSTR(@Sentence, 'k')), 'k', 'i'),
   -> SUBSTRING(@Sentence, INSTR(@Sentence, 'k') + 1)) as ChangeOnlyOneTime;

The following is the output displaying only the first occurrence of a character is replaced −

+------------------------+------------------------+
| NewString              | ChangeOnlyOneTime      |
+------------------------+------------------------+
| Thks ks is a my string | This ks is a my string |
+------------------------+------------------------+
1 row in set (0.00 sec)

Updated on: 30-Jul-2019

138 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements