READPAST and NOLOCK What are they?

8

What is READPAST and NOLOCK ?

I have seen quite a lot of the use of NOLOCK , but READPAST saw use now, pretty much the same way, ie.

FROM dbo.table t WITH(READPAST) 

and

FROM dbo.table t WITH(NOLOCK)

But what's the difference between them? And when should we use one or the other?

    
asked by anonymous 31.08.2017 / 19:55

2 answers

7

These clauses are tips for queries optimizer to meet some demand better, in general should only be used when you are sure you need a data access semantics other than the default. It can have dire consequences if you do not know what you are doing.

  • NOLOCK - ignores the locking of rows that are being updated in another transaction and accesses the data even in a potentially inconsistent state. So you can get inconsistent data.
  • READPAST - ignores only page crashes, but not crashes on lines. It tends to pick up inconsistent data but the chance is less.

Documentation .

    
31.08.2017 / 20:02
4

Compare SQL Server NOLOCK and READPAST Table Hints

TL; DR

CREATE TABLE TESTE ( ID INT NOT NULL PRIMARY KEY, VALOR CHAR(1) )
INSERT INTO TESTE(ID,VALOR)
VALUES (1,'A'),(2,'B'),(3,'C')

Run this instruction in a SQL

BEGIN TRANSACTION Transaction1
DELETE FROM TESTE
WHERE ID=1

UPDATE TESTE
SET VALOR= 'D' 
WHERE VALOR='C'

INSERT INTO TESTE(ID, VALOR)
VALUES(4,'E'),(5,'F') GO WAITFOR DELAY '00:00:05'
ROLLBACK

In another window also

SELECT * FROM TESTE WITH (NOLOCK)

The result will be :

Aftercompletingthefirsttransaction,rotatetheselectagain,seethattheresulthaschanged.

Didyounoticethedifference?

ByusingtheNOLOCKhintnotonlycanyoureadmodifieddatabutalsoreadincorrectdata,whichisaresultofchangesinthephysicallocationofdatamadebyothertransactions.(Asshownintheaboveexample)

ChangingtoREADPAST

SELECT*FROMTESTE(READPAST)

Result:

ThisisbecausethisistheonlyrowthathasnotbeenmodifiedbyTransaction1

CONCLUSION

NOLOCKallowsreadingofdirtylines(linesbeingusedbyothertransactions)andcancauseconsistencyproblemsduringTable/IndexScanoperations.NOLOCKcangreatlyimproveperformance( Como usar SELECT WITH NOLOCK para melhorar a Performance? ), but be careful about this, see the Efeitos colaterais do WITH (NOLOCK) – Parte I read lines that are not being used by other transactions.

I recommend reading:

31.08.2017 / 20:31