113

I'm looking for a way to update just a portion of a string via MySQL query.

For example, if I have 10 records all containing string as part of the field value, is there a way to change string to anothervalue for each row via one query?

I.e. for the following:

Change something/string, something/stringlookhere, something/string/etcetera to something/anothervalue, something/anothervaluelookhere, something/string/etcetera

General Grievance
  • 4,555
  • 31
  • 31
  • 45
n00b0101
  • 6,863
  • 17
  • 42
  • 36

3 Answers3

258

I think this should work:

UPDATE table
SET field = REPLACE(field, 'string', 'anothervalue')
WHERE field LIKE '%string%';
Madara's Ghost
  • 172,118
  • 50
  • 264
  • 308
Kaleb Brasee
  • 51,193
  • 8
  • 108
  • 113
27
UPDATE `table` SET `field` = REPLACE(`field`, 'string', 'anothervalue')
Matt Fletcher
  • 345
  • 3
  • 15
Tatu Ulmanen
  • 123,288
  • 34
  • 187
  • 185
14

Use the LIKE operator to find the rows that you care about and update them using the REPLACE function.

For example:

UPDATE table_name SET field_name = REPLACE(field_name,'search','replace') WHERE field_name LIKE '%some_value%'
eebbesen
  • 5,070
  • 8
  • 48
  • 70
Bernard Chen
  • 6,437
  • 5
  • 23
  • 27