Is there any real world difference in the following two SQL statements (updates that result in no net change)

StackOverflow https://stackoverflow.com/questions/22776513

Pergunta

Say I have a table 1 million rows and lets say 50% on the particular column is null (so 500k NULL and 500k non NULL). And I want to set all the rows to NULL.

Assume no indexing to simplify the domain.

UPDATE 
    MyTable 
SET 
    MyColumn = NULL

or

UPDATE 
    MyTable 
SET 
    MyColumn = NULL 
WHERE 
    MyColumn IS NOT NULL

Logic dictates that the latter is more efficient. However won't the optimiser realise the first is the same as the second as the WHERE condition and the SET only reference MyColumn.

Foi útil?

Solução

The optimizer works against SELECT statements.
The optimizer does not affect how a table is Updated.
When you ask SQL-Server to updated Every row, then it will Update EVERY Row.
It will also take a lot longer to do this because you're affecting every row; which I believe means it will affect your transaction log too.

Be VERY Careful NOT do this.
You will create Exclusive Locks on EVERY Record in the entire table when this happens.
Even if the data is not actually changing, SQL-Server will still update the record nonetheless.
This Might Cause Deadlocks on that table if another process tries to use it during that time.

I speak from experience where every night our main database table would lock up for 15 minutes while a process (someone else wrote) was updating the entire table... Twice.
This caused all the other queries to wait for it to complete (some would timeout).
Not even a simple Select statement could be run against it while it was Updating.

Outras dicas

The optimizer will not realize that the first is the same as the second.

You should use the second form. The first form will log the changes to the records that are not actually changed under some circumstances (but perhaps not in this particular case). Here is a good reference on this subject.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top