What you will be able to do
- Explain why updating an indexed column costs a delete plus insert, not an edit.
- Diagnose whether an update is bound by the query plan, lock contention, logging, or index maintenance.
- Batch a mass update so it neither escalates to a table lock nor rolls back the whole range.
- Describe row movement - key updates, page splits, forwarded records on heaps - and the fragmentation it causes.
- Choose an update pattern that is safe under concurrency.
Concepts covered
An UPDATE is the only operation that can move a row. That single fact explains most of its cost:
touch a key column and the engine deletes the entry from one place in the index and inserts it in
another; grow a row past its page and the row has to move or be forwarded. A mass update is where
lock escalation, log growth, and index maintenance arrive together.
The analogy is amending folders in a filing cabinet. Correcting a note inside a folder is a cheap edit - the folder stays where it is. Changing the label the folder is filed under is not an edit at all: the folder comes out of one slot and is re-shelved wherever the new label sorts, which is why touching an indexed column costs a delete plus an insert. Grow the folder past its slot and it is moved, with a redirect slip left behind in the old place. Re-label the entire aisle at once and it gets cordoned off while the work runs.
Which resource binds - the UPDATE diagnosis
Slow UPDATE - the four candidates
Is the seek slow?
The WHERE clause has no usable index - a scan to find a few rows
Plan shows a scan; fix is the index or the predicate, same as a SELECT
Blocking?
LCK_M waits; dm_exec_requests shows a blocker
Another transaction holds the rows - shorten it, or the update is touching too many
Escalated?
Crossed 5,000 row locks - now holding a table X lock
The whole table is now exclusive - everyone else queues; batch under the threshold
Log or maintenance?
WRITELOG high; or index maintenance dominating CPU
The write itself is the cost - batch smaller, or the indexed column is the real culprit
The real cost of touching an indexed column
Updating a column that is part of an index key is not an edit - it is a delete plus an insert
in that index: remove the old key entry, write the new one where it now belongs, possibly split a
page. Update a column in five index keys and one statement does ten index writes plus the row
change. Updating a column only in an INCLUDE list is cheaper but still touches the index leaf.
Updating a column that is in no index is the cheapest case - a pure row edit plus the log record.
-- Expensive: key columns move the entry in the index
UPDATE orders SET status = 'closed' WHERE created_at < @cutoff; -- status is a key
-- Cheaper: a non-key, non-INCLUDE column is an in-place edit
UPDATE orders SET internal_note = 'purged' WHERE created_at < @cutoff;
Lock escalation - the 5,000-lock cliff
A single statement acquiring at least 5,000 locks on one table reference triggers an escalation
attempt to a table-level lock - and the engine checks at every 1,250 locks. Once escalated, the
whole table is exclusive: every reader and writer queues. A mass UPDATE that crosses the
threshold is the classic way a “quick backfill” takes a table offline.
- The trigger is per statement, per reference - 3,000 locks on each of two indexes does not fire it.
ALTER TABLE ... SET (LOCK_ESCALATION = AUTO)escalates to partition level on a partitioned table - the one useful lever.LOCK_ESCALATION = DISABLEexists but trades the table lock for lock-memory exhaustion - a swap, not a fix.
Batching the mass update
The honest pattern keeps each commit under the escalation threshold and gives checkpoints room:
DECLARE @rows INT = 1;
WHILE @rows > 0
BEGIN
UPDATE TOP (4000) dbo.orders SET status = 'closed'
WHERE created_at < @cutoff AND status = 'open';
SET @rows = @@ROWCOUNT;
-- each iteration is its own commit - under 5,000, bounded rollback
END
The batch size is a knob, not a constant: under 5,000 avoids escalation, smaller reduces the lock window and log flush, larger reduces round trips. Pick the value that stays under the 5,000-lock escalation and keeps the lock window inside the SLA - measure it, do not inherit it.
Row movement and fragmentation
- Key update - the index entry moves; the row’s neighbours in the index change.
- Variable-width growth - a
varcharupdate that makes the row longer may not fit the page; on a clustered index it causes a page split; on a heap it becomes a forwarded record with a pointer - both fragment the table and cost extra reads later. - Row-version cost - under RCSI or SNAPSHOT every update writes a row version to tempdb too, so a mass update under row versioning pays the version store on top of the log.
Concurrency-safe patterns
- Update through a unique key seek, not a range scan, to hold the narrowest lock.
- Keep the transaction to the single statement - do work outside the lock window.
- For a read-modify-write, take
UPDLOCKon the read to prevent the update-intent deadlock two sessions create when both read then both write. - Never
UPDATEwithout a selectiveWHEREunless you meant to touch the table - and if you did, batch it.
The diagnostic toolkit
-- Is the update scanning to find rows, or blocked
SELECT r.session_id, r.wait_type, r.blocking_session_id, r.logical_reads, r.cpu_time
FROM sys.dm_exec_requests r WHERE r.command = 'UPDATE';
-- Expected: high logical_reads + no blocker = a scan (index problem);
-- LCK_M waits + a blocker = contention.
-- Locks held, at what granularity - escalation watch
SELECT request_mode, request_type, resource_type, COUNT(*) AS lock_count
FROM sys.dm_tran_locks GROUP BY request_mode, request_type, resource_type
ORDER BY lock_count DESC;
-- Expected: thousands of KEY/RID locks climbing toward 5,000; a TABLE X lock = escalated.
What to measure, before and after
| Metric | Instrument | The pass criterion |
|---|---|---|
| Lock granularity | sys.dm_tran_locks |
Batching keeps each commit under ~5,000 - no TABLE lock |
| Rows per commit | @@ROWCOUNT in the loop |
A bounded batch, not one giant transaction |
WRITELOG |
Wait-stats delta | Smaller commits reduce flush pressure but add flushes - the balance is measured |
| Blocking of readers | The other session’s wait | A reader survives the mass update without a long stall |
Advanced exercise and answer key
Exercise. A mass UPDATE t SET flag=1 (touching 2M rows, no selective WHERE) must run during
business hours. Two colleagues propose: run it as one transaction but at READ COMMITTED (it is the
default anyway), or batch it. Explain why the first does not help and design the batching plan.
Answer. Isolation level does not change the write locks - the update takes X locks regardless
and escalates at 5,000. Batching: UPDATE TOP (4000) ... WHERE flag = 0 in a committed loop - each
commit stays under the escalation threshold, bounds the rollback, lets readers interleave between
commits. Add LOCK_ESCALATION = AUTO on a partitioned table for partition-level scope. The loop
stops when @@ROWCOUNT = 0; a final single UPDATE ... WHERE flag=0 catches stragglers.
Guided practice
A beginner exercise, worked step by step in a scratch database. It makes the escalation cliff visible and then keeps the same work under it. You need a table with more rows than the escalation threshold and, ideally, a second session to watch the locks.
- Build the orders table. Run
CREATE TABLE dbo.orders (order_id INT IDENTITY PRIMARY KEY, status VARCHAR(20) NOT NULL, created_at DATETIME2 NOT NULL, internal_note VARCHAR(50) NULL);and fill it with more than five thousand rows -INSERT ... SELECToffsys.all_objectscrossed with itself is enough. Check: the row count exceeds the escalation threshold - a table that cannot reach five thousand locks cannot demonstrate the cliff. - Watch the escalation happen. Open a transaction and run
UPDATE dbo.orders SET status = 'closed' WHERE status = 'open';without committing. In a second session run the file’s lock query groupingsys.dm_tran_locksbyresource_type. Check:KEYlocks climb and then collapse into aTABLEXlock - that is escalation. If you only ever see row locks, the statement stayed under the threshold - add rows and revisit the 5,000-lock section. Roll back or commit when you have seen it. - Batch the same update under the threshold. Run the file’s loop shape -
UPDATE TOP (4000) dbo.orders SET status = 'open' WHERE status = 'closed';insideWHILE @rows > 0driven by@@ROWCOUNT- while watchingsys.dm_tran_locksagain. Check: each commit stays under the threshold and noTABLElock appears, so a reader gets in between commits. If a table lock still fired, the batch size crept over - revisit the batching section. - Compare a key-column update with a plain one. With an index whose key contains
status, runSET STATISTICS IO, TIME ON, updatestatusfor a fixed set of rows, then updateinternal_notefor the same set. Check: the key-column update writes more - the index entry is deleted and re-inserted, not edited in place. On a small set the difference can be hard to see; the mechanism is the point, so revisit the indexed-column cost if both looked identical. - Say why
UPDLOCKexists on a read-modify-write. State the failure it prevents. Check: the update-intent deadlock - two sessions both read a row and then both write, and each waits on the other.UPDLOCKon the read serialises them before either writes. Revisit the concurrency-safe patterns if you answered “it makes the read faster”.
Check your understanding
Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.
- Why is updating a column that is part of an index key more expensive than updating a column in no index? A key value lives at a sorted position, so changing it removes the old index entry and inserts a new one elsewhere - a delete plus an insert per index, possibly with a page split. A column in no index is a pure row edit plus the log record. Revisit the indexed-column cost.
- What happens when a single statement acquires 5,000 locks on one table reference? The engine attempts escalation to a table-level lock - checked at every 1,250 locks - and the whole table becomes exclusive until the transaction ends. The trigger is per statement and per reference, not a transaction total. Revisit the escalation section.
- What does batching a mass update with
TOP (4000)actually change, and what does it not? It keeps each commit under the escalation threshold, bounds the rollback to one batch, and lets readers interleave between commits. It does not reduce the total rows logged - revisit the batching section if you answered “it writes less to the log”. - An update makes
varcharrows longer. What are the two physical outcomes, and on which structures? On a clustered index a page split; on a heap a forwarded record with a pointer left behind - both fragment the table and cost extra reads later. Revisit row movement if you said the row just grows in place. - A colleague proposes running a mass update at
READ COMMITTEDso it will not block readers. Why does that not help? Isolation level does not change write locks - the update takesXlocks and escalates at 5,000 regardless of the read semantics. The fixes are batching under the threshold, or partition-level escalation withLOCK_ESCALATION = AUTOon a partitioned table. Revisit the advanced exercise.
Where SQL Server sits
How this component relates to the rest of the stack. Items without a link are not covered here yet.
Deployed with
Commonly run alongside
- Windows Failover Clustering