Find and Replace in MySQL

by Melvin Ram

Even though Rails shields us from having to resort to SQL, it’s still good to know how to do things directly. One thing I wanted to do today was find all the records that contain “blahblahblah” and replace it with “blah_dee_blah_dee_blah”. Here’s how I did it:

update wp_3_posts
set POST_CONTENT = replace(POST_CONTENT,
'http://www.volcanicmarketing.com/wp-content/',
'http://volcanic.sitespress.net/wp-content/uploads/');

As you may or may not have guessed, this wasn’t for a Rails app. It was for my WordPress system. I had moved from single wordpress sites to a server that runs WordPress Mu. One of the changes that resulted from this was that images contained inside my posts didn’t automatically adjust. The above code fixes this. Let’s deconstruct it by looking at by looking at the structure of the command:

update TABLE_NAME
set FIELD_NAME = replace(FIELD_NAME,
'find this string',
'replace found string with this string');

I got the info from http://www.mydigitallife.info/2007/04/23/how-to-find-and-replace-text-in-mysql-database-using-sql/

Leave a Comment