Search code examples
sqlmysqlif-statementsql-update

MySQL: update field only if condition is met


Is it possible to do UPDATE query on MySQL which updates field value only if certain condition is met? Something like this:

UPDATE test
SET
    CASE
        WHEN true
        THEN field = 1
    END
WHERE id = 123

In other words, "field" would be only updated if condition is met, otherwise nothing is done.

UPDATE: my example query didn't exactly specify my problem in full, because there might be more fields to be updated without conditions, in other words:

UPDATE test
SET
    something = 1,        /*field that always gets updated*/
    CASE
        WHEN true
        THEN field = 1    /*field that should only get updated when condition is met*/
    END
WHERE id = 123

Sorry for the lack of info.


Solution

  • Yes!

    Here you have another example:

    UPDATE prices
    SET final_price= CASE
       WHEN currency=1 THEN 0.81*final_price
       ELSE final_price
    END
    

    This works because MySQL doesn't update the row, if there is no change, as mentioned in docs:

    If you set a column to the value it currently has, MySQL notices this and does not update it.