Updating Substring in Column in MySQL

By | July 25, 2008

Today I needed to make the same kind of update to a field in a few rows of a large database table. There were too many rows to do it with a separate SQL update statement per row, so I hunted down the MySQL REPLACE function. Okay, it was only 6 rows, but I needed to make the same change in a dev, QA and production database. The example in the documentation is pretty trivial, but it wasn’t too hard to expand it to conditionally replace the substring.

mysql> help replace;
Name: 'REPLACE'
Description:
Syntax:
REPLACE(str,from_str,to_str)
Returns the string str with all occurrences of the string from_str
replaced by the string to_str. REPLACE() performs a case-sensitive
match when searching for from_str.
URL: http://dev.mysql.com/doc/refman/5.1/en/string-functions.html
Examples:
mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwWw.mysql.com'

The UPDATE query below is pretty similar to what I needed to do, i.e., remove some characters from the end of a varchar column. The LIKE clause I’ve used in the query ensures that “cruft” is replaced only if it appears at the end of the string.

mysql> CREATE TABLE tbl (col varchar(20));
Query OK, 0 rows affected (0.41 sec)

mysql> INSERT INTO tbl VALUES ('cruft_front'), ('some_cruft_in_middle'), ('end_cruft');
Query OK, 3 rows affected (0.00 sec)
Records: 3  Duplicates: 0  Warnings: 0

mysql> UPDATE tbl SET col = REPLACE(col, 'cruft', '') WHERE col LIKE '%cruft';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> select * from tbl;
+----------------------+
| col                  |
+----------------------+
| cruft_front          | 
| some_cruft_in_middle | 
| end_                 | 
+----------------------+
3 rows in set (0.00 sec)

4 thoughts on “Updating Substring in Column in MySQL

  1. Amin007

    well, this function REPLACE(str,from_str,to_str)
    is very cool hehehe 😀
    if not i think i must use excel to replace huhuhu

    Reply
  2. Jaymie

    Thanks for posting this – I had a problem with my Drupal 5 installation, where I’d inadvertently copied a modules folder into my existing modules folder, and the system table got updated with these references.

    Anyway, this code allowed me to delete the nested folder and update the references correctly. Thank you.

    Reply
  3. Kees Epema

    I had one table where the column col contained 17 characters. I had to update the character on the 14th position in that field. When the 14th position contained a ‘1’, it should update to ‘0’
    This statement worked, thanks to the replace mysql attention in your article, it works like a charm.
    Thanks a bunch!

    UPDATE `tbl SET `col` = REPLACE(`col`, ‘1’, ‘0’) WHERE substr(`col`,14,1) = ‘1’

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.