Click here to Skip to main content
Click here to Skip to main content

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

By , 12 Sep 2012
Rate this:
Please Sign up or sign in to vote.

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)

About the Author

aasim abdullah
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.
Follow on   Twitter   Google+

Comments and Discussions

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

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140415.2 | Last Updated 12 Sep 2012
Article Copyright 2012 by aasim abdullah
Everything else Copyright © CodeProject, 1999-2014
Terms of Use
Layout: fixed | fluid