SQL SERVER – Locking Hints with Correct Scope and Safe Examples

Locking Hints change how a table reference participates in locking. I choose the required consistency before changing the query.

A gouache garden gate has three distinct latch mechanisms, with a vermilion pin beside weathered timber and iron fittings.

I previously included DBLOCK in this list. It isn’t a valid SQL Server table hint. Valid granularity hints include ROWLOCK, PAGLOCK and TABLOCK. They don’t eliminate lock escalation or other locking requirements.

Choose the behavior deliberately

  • UPDLOCK requests update locks for reads and holds them to transaction completion.
  • HOLDLOCK applies serializable semantics to that table reference for the transaction.
  • XLOCK requests exclusive locks held to transaction completion.
  • NOLOCK is equivalent to read uncommitted for data access. It permits inconsistent results and still takes schema-stability locks.

NOLOCK isn’t the default isolation level. It doesn’t provide a supported escape from UPDATE or DELETE target-table locking. SQL Server ignores those target-table hints.

A bounded syntax example

CREATE TABLE #Orders (OrderID int PRIMARY KEY, CustomerID int NOT NULL);
INSERT INTO #Orders VALUES (1,10),(2,20);
BEGIN TRANSACTION;
SELECT OrderID, CustomerID
FROM #Orders WITH (UPDLOCK, HOLDLOCK)
WHERE OrderID = 1;
ROLLBACK TRANSACTION;
DROP TABLE #Orders;

This temporary-table example demonstrates syntax and cleanup. One session can’t prove a concurrency or blocking claim. A real concurrency demonstration requires a second session and an explicit transaction timeline.

Reference: SQL Server table hints.

Related reading

A locking hint is not a concurrency guarantee, it is a request with specific transaction semantics.

Published by Pinal Dave on SQLAuthority. More of my work at pinaldave.com.


Discover more from SQL Authority with Pinal Dave

Subscribe to get the latest posts sent to your email.

SQL Lock, SQL Scripts, SQL Server
Previous Post
SQL SERVER – Difference Between Unique Index vs Unique Constraint
Next Post
SQL SERVER – Query to Retrieve the Nth Maximum Value

Related Posts

185 Comments. Leave new

  • Hi Pinal,

    I have question like , we will be doing the data scanning and it will make entry in the table , and in the same time i need to fetch the maximum id from the table . i cannot stop the scanning .. but how will fetch the max id from that table when the scanning is continuous. whick lock needs to be implemented .

    Reply
  • bujji.skillfurys@gmail.com
    January 28, 2016 12:05 pm

    in sql server database,as per our requirement we have protect one table values.how to lock single table

    Reply
  • I guess.. Rowlock and nolock should be in reverse query.. :)

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *

Fill out this field
Fill out this field
Please enter a valid email address.