Use CASE to select columns in UPDATE query?

If you specify a column should be updated then it will always be updated, but you can change the value you put in conditionally and put back the original values depending on your conditions. Something like:

UPDATE some_table
SET    column_x = CASE WHEN should_update_x THEN new_value_for_x ELSE column_x END
     , column_y = CASE WHEN should_update_y THEN new_value_for_y ELSE column_y END
     , column_z = CASE WHEN should_update_z THEN new_value_for_z ELSE column_z END
FROM   ...

So if the conditions are not right for an update to a particular column you just feed back it's current value.

Do note that every row matched will see an update (even if all the columns end up getting set to the values they already have) unless you explicitly gate this circumstance in you filtering ON and WHERE clauses, which could be a performance problem (there will be a write, indexes will be updated, appropriate triggers will fire, ...) if not mitigated.


How many different combinations of columns to update do you have? How many rows of the entire table will be updated? Are indexes in place for fast access to rows to update?

Depending on the answers to these questions you may be able to execute multiple update statements, one for each column that you wish to update and place the condition on that column's value in the where clause of the update so that zero rows are updated if that column has the wrong value.

Try and think set-based, don't assume that update needs to update a single row found by the primary key.