Click here to Skip to main content
15,879,326 members
Articles / Desktop Programming / ATL

SQL Server: Why we should avoid the NOLOCK table hint in DELETE/UPDATE queries

Rate me:
Please Sign up or sign in to vote.
1.00/5 (1 vote)
12 Sep 2012CPOL1 min read 25.2K   2   1
Why we should avoid the NOLOCK table Hint in DELETE/UPDATE queries.

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.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Team Leader CureMD
Pakistan Pakistan
Aasim Abdullah is working as SQL Server DBA with CureMD (www.curemd.com) based in NY, USA. He has been working with SQL Server since 2007 (Version 2005) and has used it in many projects as a developer, administrator, database designer. Aasim's primary interest is SQL Server performance tuning. If he finds the time, he like to sketch faces with graphite pencils.

Comments and Discussions

 
SuggestionFormat: Put a line gap in the paragraphh Pin
Sandip.Nascar12-Sep-12 7:11
Sandip.Nascar12-Sep-12 7:11 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.