📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

📚 Interview question

How does locking work in SQL Server? Explain the main lock modes (shared, update, exclusive and the intent locks), lock granularity from row to table, which modes are compatible, and what lock escalation is and when it happens.

SQL Server lock modes (S, U, X, IS, IX, SIX, Sch-S, Sch-M), the compatibility matrix, row, page and table granularity, the lock hierarchy, lock escalation thresholds and how to control it.

Intermediate Theory Intermediate concurrency dmv lock-escalation locking sql-server transactions

🎯 Key points

  • S locks for reads, X for writes (X held to end of transaction)
  • U lock prevents the classic S-to-X conversion deadlock
  • Intent locks (IS, IX, SIX) on page and table signal finer locks below, making table-level conflict checks cheap
  • Compatibility: S/S yes, S/X no, U/U no, IX/S no
  • Key-range locks under serializable lock gaps to prevent phantoms
  • Schema locks: Sch-S for queries, Sch-M for DDL, incompatible with everything
  • Escalation at about 5,000 locks on one object in one statement, to table (or partition with AUTO), never to page
  • Inspect with sys.dm_tran_locks and LCK_M_* waits

⏱ 30-second answer

SQL Server locks resources in a hierarchy: rows (keys or RIDs), pages, and objects. Reads under read committed take shared (S) locks, writes take exclusive (X) locks held until commit, and updates first take an update (U) lock while searching so two updaters can't deadlock converting S to X. Before locking a row, SQL Server puts intent locks (IS, IX) on the page and table so a table-level request can see conflicts cheaply. S is compatible with S; X is compatible with nothing.

Lock escalation swaps many row or page locks for one table (or partition) lock when one statement holds about 5,000 locks on an object, or under memory pressure. It saves memory but can block the whole table, which is the trade-off.

🗣 Full answer (senior)

How I would answer this in an interview

"SQL Server uses locks to provide isolation. The main modes are shared for reading, exclusive for writing, and update, which is taken while an UPDATE or DELETE is finding rows. The U lock exists to avoid a classic deadlock: if two sessions both read a row with S and then both try to convert to X, each waits for the other. Only one session can hold U on a resource, so the second one waits early instead.

Locks are taken at different granularities: a key in an index or a RID in a heap, a page, or the whole object. To make that efficient there are intent locks: before I take an X lock on a row, I take IX on the page and on the table. Then if someone wants a table-level S lock, the engine sees the IX at table level and knows there's a conflict without checking every row. Schema locks are separate: queries take Sch-S, and an ALTER TABLE needs Sch-M, which is why an online index operation or migration can queue behind a long query and then block everyone behind it.

Lock escalation is the engine trading thousands of fine locks for one coarse lock. When a single statement holds about 5,000 locks on one table, it tries to escalate to a table lock, or to a partition lock if the table is set to LOCK_ESCALATION = AUTO. It never escalates to page. The mistake I see is a batch job that deletes 100,000 rows in one statement, escalates to a table X lock, and blocks the whole order table for a minute. The fix is batching under the threshold, or the right index so fewer rows are touched, not a hint. Locks are cheap until they're not, and escalation is usually where they stop being cheap."


Lock modes

Mode Taken by Notes
S (shared) SELECT under read committed or higher Released after the read under read committed; held to commit under repeatable read and serializable
U (update) UPDATE/DELETE while locating rows; UPDLOCK hint Converts to X when the row qualifies
X (exclusive) INSERT, UPDATE, DELETE Held until the transaction ends, at every isolation level
IS / IX / SIX Parent page and table of a finer lock Make coarse-grained conflict checks cheap
Sch-S / Sch-M Queries / DDL Sch-M is incompatible with everything, including Sch-S
Key-range Serializable range scans Prevents phantoms

Compatibility (simplified)

Requested \ Held IS S U IX X
IS yes yes yes yes no
S yes yes yes no no
U yes yes no no no
IX yes no no yes no
X no no no no no

Production example

A nightly purge deleted about [200,000] audit rows in one statement; it escalated to a table X lock and API writes to that table timed out for [90] seconds. Rewriting it as a loop deleting 4,000 rows per transaction kept it below the escalation threshold, and the timeouts went to zero while the purge took only slightly longer.

🔍 What the interviewer is checking

Checks that the candidate understands the lock hierarchy and escalation well enough to explain real blocking.

Green flags

  • Explains the purpose of U and intent locks
  • Knows escalation goes to table or partition at about 5,000 locks
  • Proposes batching or indexing rather than hints
  • Mentions sys.dm_tran_locks or LCK_M_* waits

Red flags

  • Says row locks escalate to page locks
  • Thinks reads never take locks at all
  • Reaches for NOLOCK as the fix

📚 Learn in depth

1. The lock manager

Locks are in-memory structures owned by the lock manager. Each has a resource (database, object, page, key hash, RID), a mode and an owner (usually the transaction). Requests that conflict queue in FIFO order; a waiting session shows LCK_M_* waits, for example LCK_M_S or LCK_M_X.

DATABASE (S, held by every connection)
  └─ OBJECT dbo.Orders     IX
       └─ PAGE 1:4402      IX
            └─ KEY (8194443284a0)  X

2. Why intent locks exist

Without intent locks, a request for a table lock would have to scan every row lock to detect conflicts. With them, a table-level request only checks the table-level entry: IX means "someone is writing below me", so a table S request must wait.

3. The U lock and conversion deadlocks

Session A: S on row  -> wants X (waits for B's S)
Session B: S on row  -> wants X (waits for A's S)   => deadlock

With U: A takes U, B requests U and waits, A converts to X, commits, then B continues. That is why UPDLOCK is the standard hint for read-then-update patterns.

4. Granularity choice

The engine picks row or page locks per statement based on estimates; it can also start with page locks for large scans. ALLOW_ROW_LOCKS and ALLOW_PAGE_LOCKS index options can restrict this, rarely a good idea.

5. Lock escalation

  • Trigger: about 5,000 locks on a single object (a single index or table/partition) acquired by one statement, checked periodically; or lock memory exceeding a threshold of memory.
  • Target: table, or partition when ALTER TABLE ... SET (LOCK_ESCALATION = AUTO) on a partitioned table. DISABLE prevents most escalation.
  • If a conflicting lock blocks escalation, the statement carries on with fine locks and retries later.
  • Trace flags 1211 and 1224 control it server-wide; prefer batching.

6. Optimized locking (SQL Server 2025, Azure SQL Database)

Optimized locking changes the picture: with transaction ID (TID) locking, a writer holds one lock on its transaction id instead of keeping row locks until commit, and lock after qualification (LAQ) evaluates predicates against the latest committed version before taking a lock. It requires Accelerated Database Recovery, and LAQ requires RCSI. It is enabled in Azure SQL Database and is opt-in per database on SQL Server 2025. It greatly reduces lock memory and escalation.

7. Seeing locks

SELECT request_session_id, resource_type, resource_description, request_mode, request_status
FROM sys.dm_tran_locks
WHERE resource_database_id = DB_ID();

The lock_escalation Extended Events event records each escalation.

Try it yourself

  1. Begin a transaction, update one row, and query sys.dm_tran_locks to see the X key lock and IX page and table locks.
  2. Update 6,000 rows in one statement inside a transaction and check whether the locks collapsed to a single OBJECT X lock.
  3. Repeat with LOCK_ESCALATION = DISABLE and compare lock counts.
  4. Reproduce the S-to-X conversion deadlock with two windows using HOLDLOCK, then fix it with UPDLOCK.

💻 Code

Observe lock modes and escalation, then avoid it by batching.

-- Window 1: hold a write lock and look at the hierarchy
BEGIN TRAN;
UPDATE dbo.Orders SET Status = 'Paid' WHERE OrderId = 42;

SELECT resource_type, resource_description, request_mode, request_status
FROM sys.dm_tran_locks
WHERE request_session_id = @@SPID;
-- KEY X, PAGE IX, OBJECT IX
ROLLBACK;

-- A purge that would escalate to a table X lock
-- DELETE dbo.AuditLog WHERE CreatedAt < DATEADD(day, -90, SYSUTCDATETIME());

-- Batched purge: each statement stays under ~5,000 locks and commits quickly
DECLARE @cutoff datetime2 = DATEADD(day, -90, SYSUTCDATETIME()), @rows int = 1;
WHILE @rows > 0
BEGIN
    DELETE TOP (4000) dbo.AuditLog WHERE CreatedAt < @cutoff;  -- needs an index on CreatedAt
    SET @rows = @@ROWCOUNT;
END

-- Partitioned table: escalate to the partition, not the whole table
ALTER TABLE dbo.AuditLog SET (LOCK_ESCALATION = AUTO);

⚠ Common mistakes

  • Mistake: Saying SQL Server escalates row locks to page locks. Why it is wrong: Escalation goes to the table or partition; page locks are chosen up front, not escalated to. Instead: Row/page to table (or partition with AUTO).
  • Mistake: Thinking S locks are held until commit under read committed. Why it is wrong: They are released as each row or page is read; only repeatable read and serializable hold them. Instead: Explain that X locks are what last until commit.
  • Mistake: Disabling lock escalation server-wide to stop blocking. Why it is wrong: Millions of row locks use lock memory and can cause error 1204. Instead: Batch large modifications and add indexes so fewer rows are locked.
  • Mistake: Ignoring intent locks when reading sys.dm_tran_locks. Why it is wrong: An IX on a table explains why a table-level request is blocked. Instead: Read the full hierarchy.
  • Mistake: Using HOLDLOCK alone for read-then-update. Why it is wrong: Two sessions both get S and deadlock converting to X. Instead: UPDLOCK, HOLDLOCK together.
  • Mistake: Forgetting schema locks during deployments. Why it is wrong: A Sch-M request waits behind a long query and blocks every new query behind it. Instead: Use WAIT_AT_LOW_PRIORITY for online index operations and deploy at quiet times.

🏛 Senior insight: trade-offs

Locking answers become strong when they explain why each mode exists: U for conversion deadlocks, intent locks for cheap hierarchy checks, escalation for memory. In practice, most locking problems are scans that lock more rows than needed, so the first fix is an index, the second is a shorter transaction, and hints come last. On Azure SQL Database, optimized locking and RCSI already remove much of the classic pain, so ask which engine and settings are in play before prescribing.

Control When it fits Cost When not to
Batching DML Purges, backfills Longer total run time Work that must be one atomic change
LOCK_ESCALATION = AUTO Partitioned tables with partition-aligned work Partition-level deadlocks possible Non-partitioned tables (no effect)
UPDLOCK hint Read-then-update in one transaction Serialises updaters of the same row Pure reads
Optimized locking Azure SQL / SQL Server 2025 with ADR and RCSI Needs ADR (persistent version store) Code relying on blocking semantics of read committed with locks

🔗 Follow-ups the interviewer may ask

  1. When: Candidate mentions blocking caused by escalation or long transactions. Why: Checks the candidate can move from lock theory to diagnosing a live incident.
    How to answer

    Blocking is sessions waiting for locks another session holds. I find the head blocker by following blocking_session_id in sys.dm_exec_requests to the session that isn't blocked itself, or with sp_WhoIsActive @find_block_leaders = 1. Then I check what it is: a running query, or a sleeping session with open_transaction_count > 0, which means the app opened a transaction and never finished it.

    Typical .NET causes: transactions left open around slow work or HTTP calls, scans caused by missing indexes locking far more rows than needed, lock escalation from big batches, and leaked connections. Mitigation may be KILL, but the fix is indexing, shorter transactions and RCSI so readers don't wait on writers.

  2. When: Candidate mentions large deletes escalating to table locks. Why: Checks the delete-and-foreign-key variant of the same problem.
    How to answer

    When you delete a parent row, SQL Server must check every child table that references it. If the child's foreign key column has no index, each check is a table scan, and the delete's locks are held for the whole long statement. A large delete also escalates to a table lock after about 5,000 locks, blocking everyone.

    I'd confirm it from the actual plan (a scan of the child under the FK check, huge logical reads) and the blocking chain (sys.dm_exec_requests, sp_WhoIsActive). The fix: index the FK columns, delete in small batches with short transactions, and avoid wide cascades. Separately, constraints created WITH NOCHECK are untrusted, so the optimiser cannot use them; re-validate with WITH CHECK CHECK CONSTRAINT once the data is clean.

  3. When: Candidate mentions serializable or range locks. Why: Checks deeper knowledge of key-range locking and phantoms.
    How to answer

    Key-range locks protect the gap between index keys so no other session can insert a row that would change the result of a range read. They appear only under SERIALIZABLE (or the HOLDLOCK hint). Modes such as RangeS-S, RangeS-U and RangeI-N combine a range part and a key part. They prevent phantoms and make upserts safe, but they need a suitable index (otherwise far more is locked), increase blocking, and are a common cause of deadlocks.

More in Transactions and Locking

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me