Reputation: 24122
I have a query that updates a column in a row where id = X
The column contains a number (1 through 3).
Is it more efficient to check the value of the column first to determine whether or not an UPDATE is needed or is it better to just UPDATE anyway even if the column value is the same as the one it's being updated to?
If I check the value first am I saving myself a needless write?
Upvotes: 2
Views: 2409
Reputation: 52893
You can do your check in the update:
update my_table
set my_column = 'new_value'
where id = 'X'
and my_column <> 'new_value'
The operative bit being, and my_column <> 'new_value'
, which will ensure that you don't update it if the value is the same.
The benefit is that you only have to query the table once and you don't do the needless write.
Upvotes: 5