I use SQL Server 2012.
I write two queries but what is a different between NOLOCK
and UnCommitted
?
SELECT lastname, firstname
FROM HR.Employees with (READUNCOMMITTED)
SELECT lastname, firstname
FROM HR.Employees with (NoLock)
I use SQL Server 2012.
I write two queries but what is a different between NOLOCK
and UnCommitted
?
SELECT lastname, firstname
FROM HR.Employees with (READUNCOMMITTED)
SELECT lastname, firstname
FROM HR.Employees with (NoLock)
No difference in terms of their functions, like other have mentioned.
The single difference is that you can apply
WITH(NOLOCK)
selectively, on some tables but not others.READ UNCOMMITTED
appliesNOLOCK
to all tables in a session.If you do this:
It is functionally equivalent to:
But you can also apply
WITH(NOLOCK)
selectively:NOLOCK : Is equivalent to
READUNCOMMITTED
(source : MSDN)NOLOCK
orREADUNCOMMITTED
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. Allowing dirty reads can cause higher concurrency, but at the cost of reading data modifications that then are rolled back by other transactionsREADUNCOMMITTED
andNOLOCK
hints apply only to data locks. All queries, including thosewith READUNCOMMITTED and NOLOCK hints
, acquire Sch-S (schema stability) locks during compilation and execution. Because of this, queries are blocked when a concurrent transaction holds a Sch-M (schema modification) lock on the tableUnder the hood they are the performing the same action.
The
read-uncommitted
isolation level is the least restrictive isolation level within SQL Server, which is also what makes it popular for developers when looking to reduce blocking.The
nolock
table hint behind the scenes performs the exact same action as running under the read-uncommitted isolation level.The only difference between the two is that the
read-uncommitted
isolation level determines the locking mechanism for the entire connection and thenolock
table hint determines the locking mechanism for the table that you give the hint to.For NOLOCK , we need to put this hint on table level, so it is require to put for every tables level which are used in update transaction. So it is very lengthy and time consuming to put it everywhere tables refers in query. For READ UNCOMMITTED, We do not need to put it every tables level, just put at session level or query level and can be written at top of the query or stored procedure. Let us look on small demo to elaborate it. First checking here database default isolation level
Output is 1, Col1 for both query
There is no difference at the statement level.
You can set READUNCOMMITED at the session level and here you have to write SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED