MySQL search and replace some text in a field

MysqlSqlSearchReplace

Mysql Problem Overview


What MySQL query will do a text search and replace in one particular field in a table?

I.e. search for foo and replace with bar so a record with a field with the value hello foo becomes hello bar.

Mysql Solutions


Solution 1 - Mysql

Change table_name and field to match your table name and field in question:

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE INSTR(field, 'foo') > 0;

Solution 2 - Mysql

UPDATE table_name 
SET field = replace(field, 'string-to-find', 'string-that-will-replace-it');

Solution 3 - Mysql

In my experience, the fastest method is

UPDATE table_name SET field = REPLACE(field, 'foo', 'bar') WHERE field LIKE '%foo%';

The INSTR() way is the second-fastest and omitting the WHERE clause altogether is slowest, even if the column is not indexed.

Solution 4 - Mysql

 UPDATE table SET field = replace(field, text_needs_to_be_replaced, text_required);

Like for example, if I want to replace all occurrences of John by Mark I will use below,

UPDATE student SET student_name = replace(student_name, 'John', 'Mark');

Solution 5 - Mysql

And if you want to search and replace based on the value of another field you could do a CONCAT:

update table_name set `field_name` = replace(`field_name`,'YOUR_OLD_STRING',CONCAT('NEW_STRING',`OTHER_FIELD_VALUE`,'AFTER_IF_NEEDED'));

Just to have this one here so that others will find it at once.

Solution 6 - Mysql

The Replace string function will do that.

Solution 7 - Mysql

I used the above command line as follow: update TABLE-NAME set FIELD = replace(FIELD, 'And', 'and'); the purpose was to replace And with and ("A" should be lowercase). The problem is it cannot find the "And" in database, but if I use like "%And%" then it can find it along with many other ands that are part of a word or even the ones that are already lowercase.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjulzView Question on Stackoverflow
Solution 1 - MysqlJoe SkoraView Answer on Stackoverflow
Solution 2 - MysqlthesmallprintView Answer on Stackoverflow
Solution 3 - MysqlGaspyView Answer on Stackoverflow
Solution 4 - MysqlUmesh PatilView Answer on Stackoverflow
Solution 5 - Mysqlbasdog22View Answer on Stackoverflow
Solution 6 - MysqlWayneView Answer on Stackoverflow
Solution 7 - MysqlSchwannView Answer on Stackoverflow