Search code examples
mysqlsqlreplacesql-scripts

Chained REPLACE functions substitute only one value at one query execution


In the tuples under Album_IDs 1 and 8 I want to replace the 'Genre' field values of 'Alternative' with emptiness (''). But when I'm executing this SQL-script, it replaces only one value at once. Is there a way to leave the half of the string (namely, 'Indie' genre, apart from 'Alternative' and the commas and spaces surrounding it) and execute the script so that all values were replaced at a heat? And what is wrong with my code?

UPDATE Album
SET Genre = REPLACE(REPLACE(Genre, ', Alternative', ''), 'Alternative, ', '')
WHERE Album_ID < 9

enter image description here


Solution

  • You can use the following using TRIM and REPLACE:

    UPDATE Album
    SET Genre = TRIM(TRIM(BOTH ',' FROM TRIM(REPLACE(Genre, 'Alternative', ''))))
    WHERE Album_ID < 9
    

    demo: http://sqlfiddle.com/#!9/3c6fe1/1/0