I have an Update statement which update several columns. Some of those columns are nvarchar(max) type and not always need to be updated.
I would like to avoid updating unnecessary columns, so, the simplest solution I come up is the following:
UPDATE table1 SET column1 = @col1, Column2= @col2, ...
TextColumn = CASE SomeVar WHEN 0 THEN @NewVal ELSE TextColumn
WHERE idTable = @idTable
Does any one know if SQL is smart enough to avoid updating the TextColumn if it is going to be updated with itself?
The second option is just to split the Update as follows:
UPDATE table1 SET column1 = @col1, Column2= @col2 ...
WHERE idTable = @idTable
IF Condition
UPDATE TextColumn = @TextVal WHERE idTable = @idTable
I do not know if there is a better alternative, maybe it is possible to dynamically choose the columns in the update sentence.
I will appreciate any suggestion about this, my main target is improve the performance of the Update
This question is similar to this one. However, that question does not address the posibility of spliting the Update statement in two sentences in order to avoid unnecessary updates. Moreover, in this case the column to update is nvarchar which involves a large amount of text which brings other performance considerations.
UPDATEstatement, whether the new value is different from the old one or not. – mustaccio May 22 '19 at 15:33TextColumnin the update and one without. Compare the times and see whether it makes a significant difference (my guess is that it doesn't). Only if it does consider implementing an optimization. – Olivier Jacot-Descombes May 22 '19 at 15:35UPDATE t SET a = 20 ;If half the rows already have 20, it'll update only the other half of the possibly million rows. – ypercubeᵀᴹ May 22 '19 at 18:15.. where a <> 20, which will also completely avoid reading the unnecessary rows as opposed to discarding them later on, after value comparison. MySQL developers just create more work for themselves by encouraging sloppy coding practices among MySQL users... – mustaccio May 22 '19 at 18:41