Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is SQL Server smart enough not to UPDATE if values are the same?

At work we've been hacking away at a stored procedure and we noticed something.

For one of our update statements, we noticed that if the values are the same as the previous values we had a performance gain.

We were not saying

UPDATE t1 SET A=5

where the column was already was equal to 5. We were doing something like this:

UPDATE t1 SET A = Qty*4.3

Anyway, is SQL Server smart enough not to do the operation if the values evaluate to the same in an UPDATE operation or am I just being fooled by some other phenomena?

like image 734
geoffrobinson Avatar asked Feb 03 '12 15:02

geoffrobinson


People also ask

Can I UPDATE same column with different values SQL?

A column cannot be assigned more than one value in the same clause. Modify the clause to make sure that a column is updated only once.

How do I know if SQL Server needs updating?

Open SSMS, click on tools. Select the check for updates. A new window will pop up, displaying the current version of SQL Server Management Studio components and the latest version available. Here, you can also enable or disable the automatic check.

How do I UPDATE conditionally in SQL?

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.

Does multiple updates in a table will decrease the performance?

The single UPDATE is faster. That is, multiple UPDATE turned out to be 5-6 times slower than single UPDATE . Save this answer.


2 Answers

Yes you will see some performance gains. I recommend reading this article to get a better understanding (it will explain why much better than I can):

https://sqlkiwi.blogspot.com/2010/08/the-impact-of-non-updating-updates.html

like image 175
Abe Miessler Avatar answered Oct 07 '22 08:10

Abe Miessler


Judging from TSQLs output, it considers the UPDATE executed even if it's to the same value.

CREATE TABLE test (id INT, val int);
GO

INSERT INTO test VALUES(1, 1);
GO
(1 row(s) affected)

UPDATE test SET val=1 WHERE id=1;
GO
(1 row(s) affected)

When it comes to the actual write to disk, I'd certainly hope that it's not needed.

Edit: See the answer from @AbeMiessler for a more in depth analysis how the write to log/disk part works.

like image 27
Joachim Isaksson Avatar answered Oct 07 '22 07:10

Joachim Isaksson