What you will be able to do
- Explain why a mass DELETE grows the log and escalates locks - and what batching actually changes.
- State when partition switching turns a purge into a metadata operation and its prerequisites.
- Choose between soft delete, batched delete, partition switch, and truncate for a retention pattern.
- Measure the rollback and ghost-cleanup cost a delete leaves behind.
- Design a retention lifecycle rather than an ad-hoc delete.
Concepts covered
A DELETE removes rows one at a time in the log and holds their locks to commit. That makes a mass
delete three problems at once - log volume, lock escalation, and rollback cost - and the diagnosis
is usually “this should not have been a DELETE at all.”
The analogy is clearing a records office by hand. Deleting is shredding every page one at a time, signing the destruction log for each sheet, and keeping the door locked to everyone else until the last page is done - abort halfway and every page comes back out of the sack. Even success is not the end of it: the emptied slots stay flagged until the cleaners make their rounds, which is the ghost cleanup. Wheeling a whole expired drawer straight to the tip - a partition switch or truncate - bypasses the per-page paperwork entirely.
The DELETE diagnosis
Slow or dangerous DELETE - the decision
How many rows?
A handful vs a mass purge
A single-row delete by key is fine - the problems start at thousands
Retention pattern?
Time-based purge of a whole range
A partition switch or truncate is near-free - DELETE logs every row
Must row-log?
FK/trigger enforcement or audit needs per-row semantics
Then batch it - commit chunks stay under the 5,000-lock escalation
Soft instead?
Mark deleted, physically purge later in a window
Buys an instant logical delete - pays it back in a cleanup job
Why a mass delete is expensive three ways
- Log volume - every removed row is a log record plus the ghost-record write. A hundred- million-row delete is a hundred-million-record log growth, which can fill the log device before the statement finishes and then roll the whole thing back - paying the cost again in undo.
- Lock escalation - past 5,000 locks on the table the engine escalates to a table
Xlock and the whole table becomes exclusive for the duration of the delete. - Rollback and ghosts - if the delete aborts, every logged row is undone. If it commits, the rows become ghost records cleaned lazily by the ghost-cleanup task, so the space returns slowly even after success.
When batching helps - and when it is overhead
WHILE 1 = 1
BEGIN
DELETE TOP (4000) FROM dbo.audit_log WHERE created_at < @cutoff;
IF @@ROWCOUNT = 0 BREAK;
-- each iteration commits; under the escalation threshold; bounded rollback
END
Batching helps when the delete must log rows (referential integrity, triggers, or a table that is
not partitioned) - it keeps each commit under the escalation threshold, bounds the rollback, and
gives the log breathing room. It is overhead when the cheaper operation exists: a whole-range
purge where TRUNCATE or a partition switch removes the data in one metadata operation without
per-row logging. Batching a delete that should have been a switch is paying the row cost N times
more politely.
The near-free alternatives
| Operation | What it does | The cost | When it is the answer |
|---|---|---|---|
TRUNCATE TABLE |
Deallocates all extents - no per-row logging | Locks the whole table briefly; resets identity; fails on a referenced FK | Emptying a table entirely |
| Partition switch | ALTER TABLE ... SWITCH swaps a partition out as metadata |
Requires the partition function, aligned indexes, and the boundary to match | Purging a whole time range - the rows leave without being deleted |
| Soft delete | UPDATE flag = 1 instead of DELETE |
The row stays - storage, index weight, and a cleanup job | When the delete must be instant and undoable; the physical purge happens off-peak |
| Batched DELETE | Rows removed in committed chunks | Still logs every row, still fragmenting | When per-row semantics are required but the volume is large |
Partition switching is the one worth knowing cold: if the table is partitioned on the retention column, purging last month’s data is swapping the partition to an empty table - an instantaneous metadata operation with no per-row logging - then dropping the switched-out table. The constraint is that the partition boundaries and index alignment must be right; it is a design decision made before the data arrives, not a rescue.
Cascading deletes, constraints, and triggers
A FOREIGN KEY ... ON DELETE CASCADE makes the parent delete ripple - one DELETE on the parent
deletes children, and each child delete logs and locks. A delete TRIGGER runs inside the
transaction and can multiply the work arbitrarily. Both multiply the log and lock cost of a mass
delete silently - the row count you see is not the row count you delete.
The lifecycle view
The right question is not “how do I delete fast” but “what is the retention design”: hot data in a
partitioned table, aged ranges switched out to archive, near-line cold data on cheaper storage, and
deletes reserved for the genuinely per-row cases. DELETE is for removing rows; retention is for
removing time ranges - and the two should not be the same operation.
The diagnostic toolkit
-- The delete's footprint: locks and log pressure
SELECT resource_type, request_mode, COUNT(*) AS lock_count
FROM sys.dm_tran_locks GROUP BY resource_type, request_mode ORDER BY lock_count DESC;
-- Expected: KEY locks climbing toward the 5,000 escalation point on a big delete.
-- Log space - the growth the delete is causing
SELECT total_log_size_in_bytes/1024/1024 AS log_mb, used_log_space_in_percent
FROM sys.dm_db_log_space_usage;
-- Expected: used percent climbing during the delete - a mass delete can fill the log.
What to measure, before and after
| Metric | Instrument | The pass criterion |
|---|---|---|
| Log bytes generated | sys.dm_db_log_space_usage delta |
A switch/truncate writes near-zero per-row log |
| Elapsed for the purge | Timed batch loop vs switch | The metadata operation is near-instant |
| Lock granularity | sys.dm_tran_locks |
Batched deletes stay under escalation |
| Space returned | sys.dm_db_index_physical_stats |
Ghost cleanup lags - space returns slowly after DELETE, instantly after TRUNCATE |
Advanced exercise and answer key
Exercise. Retention is “delete everything older than 90 days” on a 500M-row append-only table. Design the purge to run weekly without locking the table or filling the log - and name the design decision that makes it near-free.
Answer. The design decision: partition the table on the date column at create time - then
the weekly purge is ALTER TABLE ... SWITCH of the expired partition to a matching empty table
(metadata, near-instant, no per-row log) followed by DROP of the switched table. Without
partitioning, fall back to TOP (4000) batched deletes - still logging every row, still escalating
if batched wrong; the honest statement is that the cheap purge was a design choice made before
the data arrived, not an operation you can bolt on afterward.
Guided practice
A beginner exercise, worked step by step in a scratch database. It makes the log and lock cost of a mass delete visible, then shows the batched and metadata alternatives.
- Build the audit table. Run
CREATE TABLE dbo.audit_log (id BIGINT IDENTITY PRIMARY KEY, created_at DATETIME2 NOT NULL, payload CHAR(100) NOT NULL DEFAULT 'x');and fill it with enough rows that a chunk of a few thousand is a small fraction - inserts offsys.all_objectsare enough. Check: a clustered table you can delete from repeatedly without running out of rows early. - Measure the log a delete writes. Note
used_log_space_in_percentfromsys.dm_db_log_space_usage, runBEGIN TRAN; DELETE TOP (4000) FROM dbo.audit_log;, note the value again while the transaction is still open, thenROLLBACK. Check: used percent climbed - every removed row is a log record, and holding the transaction open keeps the growth visible. If it barely moved, raise the delete size - the per-row logging is the point. Revisit the three-way cost. - Watch a large delete threaten escalation. Open a transaction and delete a set larger than
five thousand rows; in a second session watch
sys.dm_tran_locksgrouped byresource_type. Check:KEYlocks climb toward the 5,000 point and then aTABLEXlock appears. Roll back when you have seen it - the rollback itself is the third cost, paying the work again in undo. - Batch the same purge. Run the file’s loop -
DELETE TOP (4000) FROM dbo.audit_log WHERE created_at < @cutoff;insideWHILE 1 = 1with@@ROWCOUNTas the exit - while watching the locks from the second session. Check: each committed chunk stays under the escalation threshold and no table lock appears. If the loop never exited, the predicate matched nothing - the exit condition and theWHEREboth matter, so revisit the batching section. - Name the near-free operation. For “drop every row older than a cutoff on a table
partitioned by that date”, name the operation and what makes it possible.
Check:
ALTER TABLE ... SWITCHthe expired partition to an aligned empty table - a metadata operation with no per-row logging - possible only because the table was partitioned on the retention column before the data arrived. If your first answer was batchedDELETE, revisit the lifecycle view: batching is the fallback when the design decision was not made.
Check your understanding
Ordered easy to hard. Answer each before reading the answer; a wrong answer names where to look.
- Why does a mass
DELETEgrow the transaction log? Every removed row is a log record plus the ghost-record write, so the log grows in proportion to the rows, not the statement - and a full log then rolls the whole thing back, paying the cost again in undo. Revisit the three-way cost if you thought the log only records the statement. - What does a large single
DELETErisk at 5,000 locks? Escalation to a tableXlock - the whole table becomes exclusive for the delete’s duration. Revisit the escalation point if you named only the wait time. - When is batching a
DELETEoverhead rather than help? When a cheaper operation exists for the job - a whole-range purge belongs toTRUNCATEor a partition switch, and batching a delete that should have been a switch is paying the row cost many times more politely. Revisit the batching section if you answered “always batch large deletes”. - Why is a partition switch nearly free, and what does it require?
ALTER TABLE ... SWITCHswaps the partition out as metadata - no per-row logging, near-instant- but it needs the partition function, aligned indexes and a matching boundary: a design decision made before the data arrived. Revisit the alternatives table.
- A delete of one parent row touched far more rows than the statement named. What made that
happen?
ON DELETE CASCADEripples the delete into the children, each child delete logging and locking, and a delete trigger runs inside the transaction and can multiply the work further - the row count you see is not the row count you delete. Revisit the cascading-deletes section.
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