What is "with (nolock)" in SQL Server?
What does the WITH (NOLOCK) hint do in SQL Server, and how does it affect query performance? Learn how it works, when to use it, and the potential risks of reading uncommitted data.
The WITH (NOLOCK) hint in SQL Server is used to query data without taking shared locks. This means the query can read data without waiting for other transactions to release their locks, which can improve performance in high-traffic databases. However, it comes with trade-offs that you should understand before using it.
Here’s what it does and why it matters:
How it works:
When you use WITH (NOLOCK), SQL Server reads data using the “read uncommitted” isolation level. This allows your query to bypass locks and avoid blocking, making queries faster.
Advantages:
- Reduces blocking issues between multiple transactions.
- Improves performance in systems with heavy read operations.
- Useful when you need quick, approximate results rather than strict accuracy.
Disadvantages / Risks:
- Can lead to dirty reads, meaning you might read uncommitted or rolled-back data.
- Possible phantom reads (rows appearing/disappearing mid-query).
- Not reliable for financial or critical data where accuracy is important.
Example:
SELECT *
FROM Orders WITH (NOLOCK);
Best Practice: Use WITH (NOLOCK) only in scenarios where performance is more important than accuracy, like generating quick reports or analyzing large datasets. Avoid using it for transactional or critical operations where data consistency matters.
In short, WITH (NOLOCK) can boost performance but should be used with caution, as it trades reliability for speed.