PostgreSQL Update with Replace – How to Guide

postgresqlpostgresql-9.4update

I am doing select which is:

SELECT replace(field_1, E'<div class="ad-content"><div class="ad-title">publicidade</div><div id=\'div-gpt-ad-1426519214388-1\'> <script type=\'text/javascript\'>googletag.cmd.push(function(){googletag.display(\'div-gpt-ad-1426519214388-1\');});</script> </div></div>', '') FROM test

An that returns what I want, but when I try to update doing the same thing, It doesn't work as expected:

UPDATE test SET field_1 = replace(field_1, E'<div class="ad-content"><div class="ad-title">publicidade</div><div id=\'div-gpt-ad-1426519214388-1\'> <script type=\'text/javascript\'>googletag.cmd.push(function(){googletag.display(\'div-gpt-ad-1426519214388-1\');});</script> </div></div>', '')

It doesn't update the column without the

<div class="ad-content"><div class="ad-title">publicidade</div><div id=\'div-gpt-ad-1426519214388-1\'> <script type=\'text/javascript\'>googletag.cmd.push(function(){googletag.display(\'div-gpt-ad-1426519214388-1\');});</script> </div></div>

Best Answer

If the SELECT works as expected, so should your UPDATE. More: it should update all columns, which is most probably not what you want.

UPDATE test
SET    field_1 = replace(field_1, $$<div class="ad-content"><div class="ad-title">publicidade</div><div id='div-gpt-ad-1426519214388-1'> <script type='text/javascript'>googletag.cmd.push(function(){googletag.display('div-gpt-ad-1426519214388-1');});</script> </div></div>$$, '')
WHERE  field_1              LIKE $$%<div class="ad-content"><div class="ad-title">publicidade</div><div id='div-gpt-ad-1426519214388-1'> <script type='text/javascript'>googletag.cmd.push(function(){googletag.display('div-gpt-ad-1426519214388-1');});</script> </div></div>%$$

I added a WHERE clause to avoid expensive and pointless empty updates.

Related: