EnjoY | Database Research And Development: MSSQL Server: Difference between NOLOCK and READPAST table hints

Saturday, August 29, 2020

MSSQL Server: Difference between NOLOCK and READPAST table hints

 – NOLOCK: Specifies that dirty reads are allowed. No shared locks are issued to prevent other transactions from modifying data read by the current transaction, and exclusive locks set by other transactions do not block the current transaction from reading the locked data. NOLOCK is equivalent to READUNCOMMITTED.

– READPAST: Specifies that the Database Engine not read rows that are locked by other transactions. When READPAST is specified, row-level locks are skipped.

Thus, while using NOLOCK you get all rows back but there are chances to read Uncommitted (Dirty) data. And while using READPAST you get only Committed Data so there are chances you won’t get those records that are currently being processed and not committed.
 

Let’s do a simple test:

–> Open a Query Editor in SSMS and copy following code:

1
2
3
4
5
6
7
8
9
10
11
12
-- Creating a sample table with 100 records:
SELECT TOP 100 *
INTO dbo.Person
FROM [Person].[Person]
 
-- Initiate Transaction to verify the behavior of these hints:
BEGIN TRANSACTION
 
UPDATE dbo.Person
SET MiddleName = NULL
WHERE BusinessEntityID >= 10
AND BusinessEntityID < 20

–> Now open a second Query Editor in SSSM and copy following code:

1
2
3
4
5
6
7
8
9
-- NOLOCK: returns all 100 records
SELECT *
FROM dbo.Person (nolock)
-- this includes 10 records that are under update and not committed yet.
 
-- READPAST: returns only 90 records
SELECT *
FROM dbo.Person (readpast)
-- because other 10 are under update and are no committed yet in the 1st Query Editor:

–> Now go back to the 1st Query Editor window and run following query to Rollback the Transaction:

1
2
3
4
5
-- Issue a Rollback to rollback the Transaction:
ROLLBACK
 
-- Drop the Sample table:
DROP TABLE dbo.Person

 

Note:

– Using READPAST avoids locking contention when implementing a work queue that uses a SQL Server table.

– Using NOLOCK may lead to read uncommitted (dirty) data and/or may read a row more than once due to page-splitting.

Both of them avoids locking, but on the cost of incorrect/dirty data. So one should carefully use them depending on their business scenario.

No comments:

Post a Comment

It’s all about friendly conversation here at small review :) I’d love to be hear your thoughts!

Be sure to check back again because I do make every effort to reply to your comments here.

Featured Post

SQL Server : SELECT all columns to be good or bad in database system

This article is half-done without your Comment! *** Please share your thoughts via Comment *** In this post, I am going to write about one o...

Popular Posts