Is it possible to do an UPDATE query in 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:
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
What is the proper way to do this?
To do a conditional update depending on whether the current value of a column matches the condition, you can add a WHERE clause which specifies this. The database will first find rows which match the WHERE clause and then only perform updates on those rows.
Yes! 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. Yes!
The UPDATE statement in SQL is used to update records in the table. We can modify one or multiple records (rows) in a table using UPDATE statement. If you do not use WHERE clause in UPDATE statement, all the records in the table will be updated.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With