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')
Scroll this instruction in a window of 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 turn as well
SELECT * FROM TESTE WITH (NOLOCK)
The result will be:
After completing the first transaction, run select again see that the result has changed.
Could tell the difference?
When using the tip from NOLOCK
not only is it possible to read modified data but also to read incorrect data, which is the result of changes in the physical location of the data made by other transactions. (As shown in the example above)
Switching to READPAST
SELECT * FROM TESTE (READPAST)
Upshot:
This is because this is the only line that has not been modified by Transaction1
CONCLUSION
NOLOCK
allows reading of dirty lines (lines that are being used by other transactions) and may cause consistency problems during Table/Index Scan
. NOLOCK
can greatly improve performance(Como usar SELECT WITH NOLOCK para melhorar a Performance?
), but be careful with that, see the Efeitos colaterais do WITH (NOLOCK) – Parte I
READPAST
read lines that are not being used by other transactions.
I recommend reading:
as well as locks made on pages?
– Jeferson Almeida
The locking can be done line by line or can lock each page, which can contain multiple lines, or can contain only a part of a line, are different shapes depending on the required granularity, then these locking will be ignored and the data is accessed, but if there is a specific lock on the line it will be respected. These things depend on deep understanding of the functioning of the database, it is not only know what it does, so it is recommended not to use until strictly necessary.
– Maniero