Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MySQL: update a field only if condition is met

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?

like image 444
Caballero Avatar asked Feb 15 '13 11:02

Caballero


People also ask

How do you update a column based on a condition?

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.

Can we use if statement in update query?

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!

Can we write update statement without WHERE condition?

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.


1 Answers

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.

like image 138
fedorqui 'SO stop harming' Avatar answered Oct 19 '22 21:10

fedorqui 'SO stop harming'