Recently, I was asked to review already written stored procedures for optimization purposes. During this review process I found a group of developers regularly
committing a big mistake. This group of developers believe that table hint NOLOCK
is used to execute queries quickly, as this hint will avoid placing any lock
on target table records and it can be used in any query. They have applied
NOLOCK
even in DML statements.
WRONG
Firstly, the NOLOCK
hint means it will not take care of any lock (instead of placing
a lock). It will return data that could be dirty (not yet committed by other transactions).
We can use this table hint to get results quickly when we are dead sure that dirty data is
totally bearable.
In DELETE
/UPDATE
queries it should be totally avoided as
it can produce junk results. Let’s prove this.
In the following example, we need to correct the discount column of SalesOrderDetail, but according to
the discount provided in the lookup table of SpecialOffer.
Before we execute our Update
statement (Statement #2 in Transaction# 2), someone accidently changes SpecialOffer, but
the good thing is that
he has not committed these changes yet. But as we have placed a NOLOCK
hint in our Statement #2 in Transaction# 2, it will change
the data according
to the dirty data, though later on transaction#1 is rolled back.