Click to search Andy Jarrett.co.uk RSS feed

Loading Twitter

Find and Replace in MySQL

I needed to do a find and replace on a couple of fields in a table and was stuck on the best way to this. Initially I was going to download a database dump and via a text editor find/replace and then re-upload but then I found out that MySQL has a Replace() function.

All you need to do is

view plain print about
1UPDATE yourTable SET yourField = replace(yourField,from_str,to_str);

The "from_str" performs a case-sensitive match when searching! Obviously you can also expand this to add any other logic like a WHERE clause etc.

This probably works with other DB's ... I would of thought anyway

Comments Comments (6) | Print Print | Send Send | 5312 Views

If you like what you see on the website and/or this post has helped you out in some way please consider donating to help keep me in beer vodka. The donations are made through Paypal, which accepts almost any credit card or eCheck.

(Comment Moderation is enabled. Your comment will not appear until approved.)
What a coincidence!

I wrote a store procedure that does the same thing for MSSQL - see here: http://blog.richnetapps.com/index.php?title=search...
I'm pretty new to MySQL (from SQLServer) and I'm trying to figure out how to do an actual regex search in my where clause for (for example to ignore punctuation in peoples nicknames). I've (temporarily) been using Replace(Replace(table.nickname,'@#',''),'!','') but that's not really acceptable to do for so many characters. If I can figure out anything better thru my googling today I'll link it for ya!
SQL server has a replace() function too. I'm not sure about Oracle, but I believe smething exists too
@Jack, MySQL has a regex function, check out REGEXP() at http://dev.mysql.com/doc/refman/5.0/en/string-comp...
William from Lagos's Gravatar Posted By William from Lagos @ 7/19/07 6:53 PM
Great tip. Just used it. You could be posting these you know.
Exactly what I was looking for! I didn't want to go through exporting sql and doing the search and replace in the file. I found software to do this but it's not free. Thanks for this tip!
BlogCFC by Raymond Camden + Twitter @AndyJ + ColdFusion jobs + Contact Me + Snippets/Downloads + RSS .