364

I have a table with the following columns in a MySQL database

[id, url]

And the urls are like:

 http://domain1.com/images/img1.jpg

I want to update all the urls to another domain

 http://domain2.com/otherfolder/img1.jpg

keeping the name of the file as is.

What's the query must I run?

Dmytro Shevchenko
  • 29,307
  • 6
  • 48
  • 64
Addev
  • 28,535
  • 43
  • 166
  • 288

6 Answers6

776
UPDATE urls
SET url = REPLACE(url, 'domain1.com/images/', 'domain2.com/otherfolder/')
Dmytro Shevchenko
  • 29,307
  • 6
  • 48
  • 64
185
UPDATE yourtable
SET url = REPLACE(url, 'http://domain1.com/images/', 'http://domain2.com/otherfolder/')
WHERE url LIKE ('http://domain1.com/images/%');

relevant docs: http://dev.mysql.com/doc/refman/5.5/en/string-functions.html#function_replace

Marc B
  • 340,537
  • 37
  • 382
  • 468
  • 13
    Hi there- why do I need the where ? – Guy Cohen Oct 07 '14 at 14:21
  • 16
    @GuyCohen Because otherwise the query will modify every single row in the table. The `WHERE` clause optimizes the query to only modify the rows with certain URL. Logically, the result will be the same, but the addition of `WHERE` will make the operation faster. – Dmytro Shevchenko Aug 14 '15 at 14:34
  • 4
    The `WHERE` also ensures that you're only replacing parts of strings that _begin_ with `http://etc/etc/` or `string_to_be_replaced.` For example, in the given answer, `http://domain1.com/images/this/is/a/test` would be affected, but `foobar/http://domain1.com/images/` would not. – Kyle Challis Jan 29 '16 at 19:03
29

Try using the REPLACE function:

mysql> SELECT REPLACE('www.mysql.com', 'w', 'Ww');
        -> 'WwWwWw.mysql.com'

Note that it is case sensitive.

schellack
  • 9,654
  • 1
  • 27
  • 32
9

You need the WHERE clause to replace ONLY the records that complies with the condition in the WHERE clause (as opposed to all records). You use % sign to indicate partial string: I.E.

LIKE ('...//domain1.com/images/%');

means all records that BEGIN with "...//domain1.com/images/" and have anything AFTER (that's the % for...)

Another example:

LIKE ('%http://domain1.com/images/%')

which means all records that contains "http://domain1.com/images/"

in any part of the string...

cabrerahector
  • 3,186
  • 4
  • 15
  • 24
Kenneth Daly
  • 91
  • 1
  • 1
8

Try this...

update [table_name] set [field_name] = 
replace([field_name],'[string_to_find]','[string_to_replace]');
Stephen Rauch
  • 40,722
  • 30
  • 82
  • 105
ManiMaran A
  • 209
  • 2
  • 5
0

First, have to check

SELECT * FROM university WHERE course_name LIKE '%&amp%'

Next, have to update

UPDATE university SET course_name = REPLACE(course_name, '&amp', '&') WHERE id = 1

Results: Engineering &amp Technology => Engineering & Technology

TechyFlick
  • 79
  • 5