Table-Level Locking Hints in SQL Server

Table-Level Locking Hints in SQL Server

Share on Facebook0Share on Google+0Tweet about this on TwitterShare on LinkedIn0Share on Reddit0

I was recently asked by a friend, how can we control the level of locking in SQL Server when executing SELECT, UPDATE, INSERT and DELETE statements.

The answer to this question is by using locking hints. Locking hints direct SQL Server to the type of locks to be used. Even though the SQL Server Query Optimizer automatically determines the best locking option when executing a statement of the above kinds, there are cases where a DBA/Database Developer might needs to explicitly control the level of locking.

The available locking hints in SQL Server are the following:

HOLDLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

NOLOCK
Applies to: SELECT

PAGLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

READCOMMITTED
Applies to: SELECT, UPDATE, INSERT, DELETE

READPAST
Applies to: SELECT, UPDATE, DELETE

READUNCOMMITTED
Applies to: SELECT

REPEATABLEREAD
Applies to: SELECT, UPDATE, INSERT, DELETE

ROWLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

SERIALIZABLE
Applies to: SELECT, UPDATE, INSERT, DELETE

TABLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

TABLOCKX
Applies to: SELECT, UPDATE, INSERT, DELETE

UPDLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

XLOCK
Applies to: SELECT, UPDATE, INSERT, DELETE

The syntax for using locking hints is very simple. You only have to add the expression with (LOCKING_HINT) just right after you are referencing a database table name (or after a table alias) in your query.

An example of using the NOLOCK locking hint within a SELECT statement is the following:

SELECT column
FROM table with (NOLOCK)

The following MSDN Library link fully describes the above locking hints.


Recommended eBooks on SQL Server:

Tuning SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Tuning SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Administering SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Administering SQL Server: eBook by SQL Server MVP Artemakis Artemiou
Artemakis Artemiou
Artemakis Artemiou is a Senior SQL Server Architect, Author, Software Developer and a Microsoft Data Platform MVP. He has over 15 years of experience in the IT industry in various roles. Among other, via his initiative SQLEBooks.com, Artemakis authors and publishes eBooks on different topics on SQL Server. Artemakis currently serves as the President of the Cyprus .NET User Group (CDNUG) and the International .NET Association Country Leader for Cyprus (INETA). Additionally he is the founder of the SQLArtBits initiative that aims to provide the technical community with simple, yet powerful and high-quality SQL Server tools. Currently, the highlights of these tools are DBA Security Advisor and In-Memory OLTP Simulator. Artemakis's official website can be found at aartemiou.com. Artemakis's blogs can be found at: SQLNetHub.com and TechHowTos.com.