Learn more about SQL Server tools

 

Tutorials          DBA          Dev          BI          Career          Categories          Events          Whitepapers          Today's Tip          Join

Tutorials      DBA      Dev      BI      Categories      Events

DBA    Dev    BI    Categories

 

Understanding the SQL Server NOLOCK hint


By:   |   Read Comments (41)   |   Related Tips: 1 | 2 | 3 | 4 | 5 | 6 | More > Locking and Blocking

Problem

I see the use of the NOLOCK hint in existing code for my stored procedures and I am not exactly sure if this is helpful or not. It seems like this has been a practice that was put in place and now is throughout all of the code wherever there are SELECT statements. Can you explain the what NOLOCK does and whether this is a good practice or not?

Solution

It seems that in some SQL Server shops the use of the NOLOCK (aka READUNCOMMITED) hint is used throughout the application. In this tip we take a closer look at how this works and what the issues maybe when using NOLOCK.

Example

Let's walk through some simple examples to see how this works. (These queries are run against the AdventureWorks database.)

Here is a query that returns all of the data from the Person.Contact table. If I run this query I can see there is only one record that has a Suffix value for ContactID = 12.

SELECT * FROM Person.Contact WHERE ContactID < 20

use of the nolock(aka readuncommited) hint

Let's say another user runs the below query in a transaction. The query completes and updates the records, but it is not yet committed to the database so the records are locked.

-- run in query window 1
BEGIN TRAN
UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID < 20
-- ROLLBACK or COMMIT

If I run the same query from above again you will notice that it never completes, because the UPDATE has not yet been committed.

-- run in query window 2
SELECT * FROM Person.Contact WHERE ContactID < 20

If I run sp_who2 I can see that the SELECT statement is being blocked. I will need to either cancel this query or COMMIT or ROLLBACK the query in window one for this to complete. For this example I am going to cancel the SELECT query.

commit or rollback query

To get around the locked records, I can use the NOLOCK hint as shown below and the query will complete even though the query in window 1 is still running and has not been committed or rolled back.

-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20

If you notice below the Suffix column now has "B" for all records. This is because the UPDATE in window 1 updated these records. Even though that transaction has not been committed, since we are using the NOLOCK hint SQL Server ignores the locks and returns the data. If the UPDATE is rolled back the data will revert back to what it looked like before, so this is considered a Dirty Read because this data may or may not exist depending on the final outcome in query window 1.

using the nolock hint sql server ignores the locks

If I rollback the UPDATE using the ROLLBACK command and rerun the SELECT query we can see the Suffix is back to what it looked like before.

-- run in query window 1
ROLLBACK

-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20
-- or
SELECT * FROM Person.Contact WHERE ContactID < 20

using the rollback command

So the issue with using the NOLOCK hint is that there is the possibility of reading data that has been changed, but not yet committed to the database. If you are running reports and do not care if the data might be off then this is not an issue, but if you are creating transactions where the data needs to be in a consistent state you can see how the NOLOCK hint could return false data.


Locks

So what kind of locking is used when the NOLOCK hint is used.

If we run our SELECT without NOLOCK we can see the locks that are taken if we use sp_lock. (To get the lock information I ran sp_lock in another query window while this was running.)

SELECT * FROM Person.Contact WHERE ContactID < 20

we can see the locks that are taken if we use sp_lock

If we do the same for our SELECT with the NOLOCK we can see these locks.

SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20

sql server still creates a lock to make sure the data is consistent

The differences are that there is a "S" shared access lock that is put on the page (PAG) that we are reading for the first 19 rows of data in the table when we don't use NOLOCK. Also, we are getting a Sch-S lock versus an IS lock for the table (TAB).

So another thing to point out is that even when you just SELECT data SQL Server still creates a lock to make sure the data is consistent.

These are the lock types and the lock modes that are used for the above two queries.

Lock Types

  • MD - metadata lock
  • DB - database lock
  • TAB - table lock
  • PAG - page lock

Mode

  • S - Shared access
  • Sch-S - Schema stability makes sure the schema is not changed while object is in use
  • IS - Intent shared indicates intention to use S locks

READUNCOMMITED

The NOLOCK hint is the same as the READUNCOMMITED hint and can be used as follows with the same results.

SELECT * FROM Person.Contact WITH (READUNCOMMITTED)

SELECT statements only

The NOLOCK and READUNCOMMITED hints are only allowed with SELECT statements. If we try to use this for an UPDATE, DELETE or INSERT we will get an error.

UPDATE Person.Contact with (NOLOCK) SET Suffix = 'B' WHERE ContactID < 20

Msg 1065, Level 15, State 1, Line 15
The NOLOCK and READUNCOMMITTED lock hints are not allowed for target tables of INSERT, UPDATE, DELETE or MERGE statements.

Schema Change Blocking

Since a NOLOCK hint needs to get a Sch-S (schema stability) lock, a SELECT using NOLOCK could still be blocked if a table is being altered and not committed. Here is an example.

-- run in query window 1
BEGIN TRAN
ALTER TABLE Person.Contact ADD column_b VARCHAR(20) NULL ;

If we try to run our SELECT statement it will be blocked until the above is committed or rolled back.

-- run in query window 2
SELECT * FROM Person.Contact WITH (NOLOCK) WHERE ContactID < 20

Issues

We mentioned above how you can get dirty reads using the NOLOCK hint. These are also other terms you may encounter for this hint.

  • Dirty Reads - this occurs when updates are done, so the data you select could be different.
  • Nonrepeatable Reads - this occurs when you need to read the data more than once and the data changes during that process
  • Phantom Reads - occurs where data is inserted or deleted and the transaction is rolled back. So for the insert you will get more records and for the delete you will get less records.

To learn more about these issues read this article: http://msdn.microsoft.com/en-us/library/ms190805.aspx


Isolation Level

You can also set the Isolation Level for all queries instead of using the NOLOCK or READUNCOMMITTED hint. The isolation level will apply the READUNCOMMITTED to all SELECT statements that are performed from when this is turned on until it is turned off.

In the example below, the two SELECT statements will use the READUNCOMMITED or NOLOCK hint and the UPDATE will still function as normal. This way you can set a whole batch of statements instead of modifying each query.

SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED; -- turn it on

SELECT * FROM Person.Contact WHERE ContactID < 20

UPDATE Person.Contact SET Suffix = 'B' WHERE ContactID = 1

SELECT * FROM Person.Contact WHERE ContactID < 20

SET TRANSACTION ISOLATION LEVEL READ COMMITTED; -- turn it off

Next Steps


Last Update:






About the author


 



More SQL Server Solutions




Post a comment or let the author know this tip helped.

All comments are reviewed, so stay on subject or we may delete your comment. Note: your email address is not published. Required fields are marked with an asterisk (*).

*Name    *Email    Notify for updates 


Get free SQL tips:

*Enter Code refresh code     



Thursday, July 21, 2016 - 5:21:01 AM - Klaus Back To Top

Nice article, indeed!
I wonder if there is a way to do select which returns the data before the other session started the transaction without beeing locked by that session.
Thanks and regards


Tuesday, July 12, 2016 - 2:19:45 AM - sivasai s Back To Top

 Nice Article. Worth reading it.

 


Thursday, June 30, 2016 - 6:19:45 AM - karthic Back To Top

 Nice one Greg Robidoux !!!

There is a case for me calling web service from SQL server ...Really fed up with not finshed(broken) code/ pieces.


Tuesday, May 03, 2016 - 5:25:40 AM - Umesh P Back To Top

 Nice Article with very good explaination with the help of examples. 

 


Friday, February 19, 2016 - 1:54:58 AM - m.h Back To Top

that is good very good.

very thanks.


Wednesday, February 03, 2016 - 10:56:11 PM - Praveen Back To Top

Thanks for teaching me this topic. You did  it very well. 

 


Thursday, October 08, 2015 - 1:36:11 PM - J Back To Top

The T-SQL code for the views in CRM 2011 make extensive use of the NO LOCK hint.

Maybe there are ways known to a select few that allow implementing the hint without any adverse consequences.


Friday, September 18, 2015 - 9:44:59 AM - Greg Robidoux Back To Top

Hi Kavitha,

the first thing to do is to see how you can tune your queries.  You can use Profiler or a server side trace to look for long running queries.  I usually start with things that run over 500ms.  From there review the query plan and see if you can make these run faster either by reworking the query or adding indexes.

Also, check the system wait stats to make sure the issue is not something SQL related. This could be CPU, memory, IO, etc. and adjust as needed.

Sorry there is not a simple answer, but this is where you should start.


Monday, September 14, 2015 - 3:42:46 AM - Kavitha Back To Top

How to improve my database performance speed?  i have using sql server 2008 r2, 100 users access my database at a time through online web application. size of database 13GB. i am not using views and Triggers. i have create more index also.


Thursday, June 18, 2015 - 8:37:48 AM - Kuldeep Back To Top

Very nice post.  

Thanks


Tuesday, April 28, 2015 - 4:35:46 PM - Herv Back To Top

Some of us are just born teachers.


Wednesday, March 11, 2015 - 10:52:31 AM - Akash Back To Top

Thank you for such wonderful explaination, Grag. It helps me to understand the concept.

 

Kind Regards,

Akash


Monday, November 03, 2014 - 5:32:00 AM - anil Back To Top

HI Grag,

Thank you for sharing this article. It halped me a lot in doing RCA for a blocking issue.

 

Br,

Anil


Tuesday, August 26, 2014 - 3:49:45 AM - Ramanagoud P Back To Top

Very simple & nice explaination.

Thank you so much.


Tuesday, August 12, 2014 - 11:24:27 AM - mkh Back To Top

Cool thanks, I was missing () in NOLOCK.


Friday, August 01, 2014 - 3:27:25 PM - Greg Robidoux Back To Top

Yes you can use NOLOCK on multiple tables if you are doing JOINS.

Read this tip too: http://www.mssqltips.com/sqlservertip/3172/avoid-using-nolock-on-sql-server-update-and-delete-statements/


Friday, August 01, 2014 - 2:24:08 PM - Boris Back To Top

Great explanation.

Nolock can be also used with Joins 


Tuesday, July 22, 2014 - 8:41:55 AM - Praveen Back To Top

 

Excellent explaination


Sunday, February 09, 2014 - 5:52:49 AM - swapnil Back To Top

 

drop  table #tmp

create table #tmp

(

spid nvarchar(200) ,    dbid int ,    ObjId int ,   IndId int ,   Type varchar(200) , Resource varchar(2000) ,     Mode varchar(200) , Status varchar(200)

)

 

insert #tmp 

exec sp_lock

 

select DISTINCT spid ,[dbid],[TYPE] , 'dbcc inputbuffer('+spid+')' as sql, 'KILL '+spid As sql 

from #tmp WHERE [TYPE] = 'TAB'

 

Tuesday, January 14, 2014 - 3:16:03 AM - Binh Nguyen Back To Top

Thanks,nice post


Wednesday, September 25, 2013 - 4:02:57 AM - Vivek Grover Back To Top

Thanks Greg

This example makes sense to understand WITH (NOLOCK)

 


Thursday, September 05, 2013 - 9:21:14 AM - Greg Robidoux Back To Top

@Ramesh - a nonreaptable read is when you need to read the same data more than once and the data changes during the process.  The nolock allows you to get uncommited transactions, so you may get different data during your transaction.  For the second question a KEY lock with an X is an exclusive lock on an index key.  You can use the ObjId and IndID to figure out which table and index by reading sys.objects and sys.indexes to find the information.


Thursday, September 05, 2013 - 5:48:04 AM - Ramesh Back To Top

Hello Greg,

Firstly thanks for ur useful article about nolock.

Secondly i need some explanation reg dirty reads and unrepeatable reads. Reading the uncommitted data is dirty raad. This is crystal clear. However I'm not clear about unrepeatable reads.

One more thing.. sp_lock showing one more type of lock with TYPE as KEY and Mode as X. Can you shed some light on this as well?

Thanks in advance!


Friday, August 16, 2013 - 2:26:39 AM - Vishanth Back To Top

good one. . . 


Friday, August 16, 2013 - 2:25:31 AM - Ramesh Narayanan Back To Top

Awesome Article! ..

Thank You.

 

 


Monday, July 29, 2013 - 5:31:52 AM - PRITESH Back To Top

Nice Artilcle ..... :)


Wednesday, May 08, 2013 - 2:08:43 PM - Greg Robidoux Back To Top

@Del Lee - I have seen people use this when the result set doesn't need to be perfect and data that is close enough is good enough. 

I would never use this for accounting type reports or where you need to get exact numbers, because you may not get the correct values.

If you want to do a quick count of records based on certain value this could help without being blocked or causing blocking, but again the numbers may not be 100% accurate.

So the bottom line is if you need the exact data at a given point in time don't use NOLOCK if the data can be close enough that it could be a candidate.  I would never just make this a standard practice you should only do this where long running queries may impact your transactions.


Wednesday, May 08, 2013 - 1:36:47 PM - Del Lee Back To Top

I'm sure I understand the NOLOCK hint, but I'm not sure I know how to apply what I know.  In other words, I'm not sure when I would ever be comfortable with a dirty read.  The general example often given when this is explained is a reporting situation, but for most reports I've done in my career allowing dirty reads would essentially create "garbage out" because data is not consistent or is out of balance.  The easiest scenario to point out would be an accounting report that looks at debits and credits.  When a user sees a report that is out of balance, then the confidence in the integrity of the data can be questioned.


Friday, May 03, 2013 - 5:37:24 AM - ghfgj Back To Top

*** NOTE *** - If you want to include code from SQL Server Management Studio (SSMS) in your post, please copy the code from SSMS and paste the code into a text editorghjghjj like NotePad before cgjghjopying the code below to remove the SSMS formatting.

ghghh


Thursday, February 21, 2013 - 7:52:50 AM - Darshan Back To Top

Hey Greg, Its really good post. The Explaination is very neat and confined what it was menat (NOLOCK) rather than squeezing all the things you know.

I understood the use of NOLOCK after reading this post.

 


Friday, February 15, 2013 - 3:49:10 AM - Suman Back To Top

Very Useful article Greg. Understood what NOLOCK actually does after reading your post. Thanks


Thursday, January 24, 2013 - 1:18:31 AM - Madhu Back To Top

 

Great work Greg..

Quick, simple and very informative.. Thanks to you..

As I have gained such a nice understanding with this, I would not like to hide that the section of 'Phatom read' was a bit unclear OR may be that you didnt want to go into much details of that probably.

The useful definintion of 'Phantom Read' i found was "Phantom reads occur when an insert or a delete action is performed against a row that belongs to a range of rows being read by a transaction. The transaction's first read of the range of rows shows a row that no longer exists in the subsequent read, because of a deletion by a different transaction. Similarly, as the result of an insert by a different transaction, the subsequent read of the transaction shows a row that did not exist in the original read." Ref: 

 

http://social.msdn.microsoft.com/Forums/en/sqldocumentation/thread/f4924482-4ce3-4e25-86fd-126c7e97a33b

 


Tuesday, January 01, 2013 - 11:04:14 AM - Greg Robidoux Back To Top

@George - yes the advantage to using this is to avoid being blocked by other processes, which could make this finish faster, and also that even running a SELECT uses locks that could cause blocking for other processing.

I would always look at this as the last option and not as the general rule.


Monday, December 31, 2012 - 4:22:19 PM - George Back To Top

Thanks for another fantastic post, Greg.  At my work, I run a lot of reports on the data.  None of the things I run are critical.  I have been asked by the DBA to add the NOLOCK hint to everything I write that hits our production database.  We do have problems periodically with locking and it slows down our production line and can occasionally cause issues out there.

It sounds like it would, indeed, be a good idea for me to use the hint.  But I wanted to be sure I understood my use of it correctly.  When I use the hint, I am saying I am okay with dirty reads.  The benefit of this is that my query can finish quicker, rather than waiting for other locks to be released and then locking it with my own query.  I am not able to do a SELECT without locking at least some part (or all) of the table.  Is that correct?


Friday, December 28, 2012 - 11:25:02 AM - Greg Robidoux Back To Top

@CodePro - you should try to avoid using this hint and only use it in extreme cases where there is a lot of blocking occuring.  As mentioned in the article when you use this hint you get dirty reads, so this should only be used if you are facing blocking issues and you can live with the dirty reads as mentioned in the Issues section.


Friday, December 28, 2012 - 10:27:37 AM - CodePro Back To Top

I'm still not geting when I should use NOLOCK. As you point out, it is a hint. Generally speaking, you should leave such decisions up to SQL Server and the OS.


Tuesday, August 21, 2012 - 1:28:37 PM - Charles Back To Top

Great post Greg.   I have personally been using NOLOCK and another hint called READPAST for various situations.  I think it's a good idea that SQL guys know the strengths of the various hints and when to use them, and your post does a good job.


Wednesday, August 17, 2011 - 7:52:44 AM - Scott C Back To Top

At a previous job we had a web developer that thought GUID primary keys were a great idea.  (Could be one of the reasons he later got canned.)

We found that SELECT COUNT(*) FROM <table with GUID PK> WITH (NOLOCK) was not accurate, even when there was no other activity in the table.  Repeatedly running the command would produce answers that varied up or down by a small amount, apparently at random.  This was in SQL 2005, don't know if it is fixed in 2008.

Other than that, it is very useful for running reports on a production database without killing all the apps.  Not very good for accurately updating bank balances.


Tuesday, August 16, 2011 - 11:38:41 AM - Greg Robidoux Back To Top

Hi Mike, yes your correct.  A SELECT still places a shared lock on the data.  I tried to show an example of this under the LOCKS section of the tip.  Since I am only doing a small set of records a PAGE lock was used, but this could get escalated to a TABLE lock as you mentioned.


Tuesday, August 16, 2011 - 11:21:56 AM - Mike Back To Top

Thanks Greg,

for this explanation. But I miss something. A select that is send to the Database can also create a LOCK-Situation if you don't use the NOLOCK statement. So not only updatestatement's can create Locks.

If you use an select statement on an bigger table with 'order' or 'group by' statements in it, you will quick notice that there are some performence Problem's on your Database. Maybe your statement will escalate the lock to an Table-Lock.

Nice overviews of Locking you will get with http://www.sommarskog.se/sqlutil/aba_lockinfo.html 

greetings from Germany

Mike


Tuesday, August 16, 2011 - 10:07:21 AM - TheSmilingDBA Back To Top

Great explanation. Thanks Greg.

I believe NOLOCK is going to be deprecated in a future version of SQL, so users might want to use READUNCOMMEITTED and not NOLOCK.

Itzik Ben-Gan has shown a case where a page split causes a double read of some data using NOLOCKs. You might wnat to BING it!!!

Thomas

 


Learn more about SQL Server tools