Learn more about SQL Server tools



solving sql server problems for millions of dbas and developers since 2006 join MSSQLTips for free SQL Server tips













































   Got a SQL tip?
            We want to know!

Understanding the SQL Server NOLOCK hint

MSSQLTips author Greg Robidoux By:   |   Read Comments (28)   |   Related Tips: 1 | 2 | 3 | 4 | 5 | 6 | 7 | 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: 8/16/2011


About the author
MSSQLTips author Greg Robidoux
Greg Robidoux is the President of Edgewood Solutions and a co-founder of MSSQLTips.com.

View all my tips


print tip Print  
Become a paid author





join MSSQLTips for free SQL Server tips     



Learn more about SQL Server tools
Post a comment or let the author know this tip helped you.

       All comments are reviewed, so stay on subject or we may delete your comment.

*Name   *Email Notify for updates



       Note: your email address is not published. Required fields are marked with an asterisk (*)


Get free SQL tips:

*Enter Code refresh code     



Tuesday, August 26, 2014 - 3:49:45 AM - Ramanagoud P Read The Tip

Very simple & nice explaination.

Thank you so much.


Tuesday, August 12, 2014 - 11:24:27 AM - mkh Read The Tip

Cool thanks, I was missing () in NOLOCK.


Friday, August 01, 2014 - 3:27:25 PM - Greg Robidoux Read The Tip

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 Read The Tip

Great explanation.

Nolock can be also used with Joins 


Tuesday, July 22, 2014 - 8:41:55 AM - Praveen Read The Tip

 

Excellent explaination


Sunday, February 09, 2014 - 5:52:49 AM - swapnil Read The Tip

 

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 Read The Tip

Thanks,nice post


Wednesday, September 25, 2013 - 4:02:57 AM - Vivek Grover Read The Tip

Thanks Greg

This example makes sense to understand WITH (NOLOCK)

 


Thursday, September 05, 2013 - 9:21:14 AM - Greg Robidoux Read The Tip

@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 Read The Tip

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 Read The Tip

good one. . . 


Friday, August 16, 2013 - 2:25:31 AM - Ramesh Narayanan Read The Tip

Awesome Article! ..

Thank You.

 

 


Monday, July 29, 2013 - 5:31:52 AM - PRITESH Read The Tip

Nice Artilcle ..... :)


Wednesday, May 08, 2013 - 2:08:43 PM - Greg Robidoux Read The Tip

@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 Read The Tip

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 Read The Tip

*** 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 Read The Tip

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 Read The Tip

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


Thursday, January 24, 2013 - 1:18:31 AM - Madhu Read The Tip

 

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 Read The Tip

@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 Read The Tip

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 Read The Tip

@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 Read The Tip

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 Read The Tip

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 Read The Tip

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 Read The Tip

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 Read The Tip

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 Read The Tip

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

 




 
Sponsor Information







Copyright (c) 2006-2014 Edgewood Solutions, LLC All rights reserved
privacy | disclaimer | copyright | advertise | about
authors | contribute | feedback | giveaways | free t-shirt | user groups | community | events | first timer?
Some names and products listed are the registered trademarks of their respective owners.