I'm trying to write some queries to fetch data from database. I used to use With(NoLock) to prevent SQL Server from placing shared locks on database. And recently a friend of mine told me that the default behavior now is that it doesn't put any lock on reading data.
However, I can't find a clean explanation for this. Should I still use With(NoLock) in SQL Server?
The benefits of querying data using the NOLOCK table hint is that it requires less memory and prevents deadlocks from occurring with any other queries that may be reading similar data. The only drawback is that using the NOLOCK table hint may accidentally result into reading uncommitted “dirty” data.
The NOLOCK hint has been deprecated in favor of READ COMMITTED SNAPSHOT (RCSI). Starting with SQL Server 2022, these hints will no longer be honored, and the transaction will operate under default isolation level (RCSI, if enabled, or READ COMMITTED if not).
The CON of using RETRIEVAL NOLOCK is the possibility of false abends. These happen when the database is being updated concurrently by other tasks, and the retrieval program accesses records whose prefixes (set pointers) are in the midst of being updated.
NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT. NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED.
WITH (NOLOCK)
behaves the same as setting the transaction isolation level to READ UNCOMMITTED
, just its scope is different.
However, keep in mind that SQL Server is allowed to use a different isolation level depending on the type of query you are running. (INSERT, UPDATE, DELETE and other write operations have to run under at least READ COMMITTED
).
Your friend is not right, SQL Server will acquire at least a schema lock during read operations on the table to prevent changes in the table's structure. This lock will be applied to the table even if you use READ UNCOMMITTED
isolation level or the WITH (NOLOCK)
hint.
In general, I would avoid using the WITH (NOLOCK)
hint. You have less control when using the table hint. Use READ UNCOMMITTED
isolation level for the connection if dirty reads are acceptable.
You can always change the isolation level of the connection, but you cannot dynamically remove the WITH (NOLOCK)
hint. This is especially true when you use WITH (NOLOCK)
on each and every table.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With