Scrivio Interview library
ScenarioIntermediate6 min read · updated 12 November 2026

A nightly SQL Server job deletes 2 million old rows with one DELETE statement, and during that time the online order API times out on the same table. Explain why and how you would rewrite the job.

One DELETE of 2 million rows takes far more than 5,000 row locks, so SQL Server escalates to an exclusive table lock, which blocks every writer and, under locking READ COMMITTED, every reader of the table until the delete commits. It also writes one huge transaction to the log and would take a long time to roll back. I would rewrite the job as a loop of small deletes, a few thousand rows each in clustered key order with a commit per batch, or, better, partition the table by date and switch out or truncate old partitions.

Why this question is asked

Clean-up jobs are usually written once, tested on a small table, and forgotten until the table grows. Then one night the online API starts timing out, always during the same hour. Interviewers ask this scenario because the fix needs three pieces of knowledge: lock escalation, transaction log behaviour, and how to batch safely. In this answer, we will see why the single DELETE blocks the API, look at its effect on the log, rewrite the job in batches with sensible ordering and sizing, consider partition switching, and weigh the escalation and snapshot options.

1Why One DELETE Blocks the Whole Table

A DELETE takes an exclusive lock on every row it removes, plus intention locks on pages and the table. SQL Server keeps row locks in memory, and when a single statement holds about 5,000 locks on one table, it tries to escalate them into one exclusive (X) lock on the whole table. Our statement will delete 2 million rows, so it passes that threshold within the first fraction of a second.

Once the table X lock is granted, it is held until the statement's transaction commits, which may be many minutes. Every API insert and update on the table needs an IX lock on the table, which conflicts with X, so they wait. Reads wait too if the database uses the default locking READ COMMITTED, because they need IS locks. The API's requests queue until its client timeouts fire.

Step throughThe nightly delete and the online API
Cleanup jobSQL ServerOrder API
DELETE FROM Orders WHERE created_at < @cutoff
5,000 row locks reached: escalate to table X
INSERT INTO Orders ... (needs IX on table)
IX conflicts with X: API waits
timeout after 30 s
delete commits after 12 minutes

6 messages in order. Play them, or step through them one at a time.

Every statement on the table waits behind one escalated lock.

2The Log and the Rollback Problem

A single statement is a single transaction, and SQL Server must log every deleted row so the transaction can be rolled back. Two million rows with their indexes can mean several gigabytes of log that cannot be truncated until the transaction ends, even with frequent log backups. Availability group replicas and log shipping have to receive all of it too.

Worse, if someone cancels the job at minute 10 because the API is down, SQL Server has to undo 10 minutes of work, and a rollback is often slower than the original work. The table stays locked during the rollback. So the cancel button does not help, which surprises people during an incident.

3Rewriting the Job in Batches

The fix is to delete in small batches, each its own transaction, so each batch stays below the escalation threshold, commits quickly and releases its locks. Between batches, the API's statements get their turn. Ordering by the clustered key makes each batch read a contiguous range of pages, and an index on created_at, or a cutoff expressed as a clustered key value, keeps each batch from scanning the whole table.

Java
DECLARE @cutoff datetime2 = DATEADD(day, -365, SYSUTCDATETIME());
DECLARE @batch int = 4000, @rows int = 1;
WHILE @rows > 0
BEGIN
WITH old AS (
SELECT TOP (@batch) * FROM dbo.Orders
WHERE created_at < @cutoff
ORDER BY id -- clustered key order
)
DELETE FROM old; -- autocommit: one short transaction per batch
SET @rows = @@ROWCOUNT; -- 4000, 4000, ..., 1520, 0
WAITFOR DELAY '00:00:00.100'; -- give online work room, let log backups keep up
END

DELETE TOP (n) on its own cannot take an ORDER BY, which is why the CTE is used: the CTE picks the next 4,000 oldest rows by id, and deleting from the CTE deletes them from the table. Each loop iteration commits by itself because no explicit transaction is open. If the job dies halfway, the committed batches stay done and the next run simply continues.

4Choosing and Measuring the Batch Size

The batch size balances throughput against blocking. It should stay comfortably below the escalation threshold, counting locks on the table's indexes too, so 2,000 to 4,000 rows is a common starting point. We then measure: the duration of each batch, which should be tens of milliseconds, not seconds; lock waits and p99 latency of the API during the job; log growth and log backup lag; and replica lag if there are secondaries.

The Extended Events lock_escalation event tells us directly whether any batch still escalated. If batches are fast and nothing escalates, we can try a larger size; if API latency rises, we shrink it or lengthen the pause.

5Partition Switching, Escalation Settings and RCSI

If the table is partitioned by created_at, for example monthly, deleting old data becomes a metadata operation. We switch the oldest partition out into an empty staging table with the same structure and truncate the staging table, or, since SQL Server 2016, truncate the partition directly. Either takes seconds and logs almost nothing, instead of deleting rows one by one.

SQL
ALTER TABLE dbo.Orders SWITCH PARTITION 1 TO dbo.Orders_Staging; -- metadata only
TRUNCATE TABLE dbo.Orders_Staging;
-- or: TRUNCATE TABLE dbo.Orders WITH (PARTITIONS (1));

Two settings reduce blocking without changing the job, but each has trade-offs. ALTER TABLE ... SET (LOCK_ESCALATION = AUTO) on a partitioned table escalates to the partition instead of the table, so the API is blocked only if it touches old partitions; LOCK_ESCALATION = DISABLE prevents most escalation but lets lock memory grow and can cause out-of-memory errors for locks. READ_COMMITTED_SNAPSHOT makes readers use row versions so they stop waiting, but writers would still wait behind the table lock, and the version store grows. Batching remains the main fix; these are complements.

6Follow-up questions

What batch size would you choose and how would you measure it?

I would start around 2,000 to 4,000 rows, below the roughly 5,000-lock escalation threshold even counting index locks, and run it in a test environment with production-like data and a load test on the API. I would measure batch duration, lock_escalation events, API p99 latency and lock waits, log usage and replica lag. Then I would tune: larger batches if everything stays quiet, smaller ones or longer pauses if API latency rises.

Does the batched job need an index on created_at?

If the cutoff is on created_at and ids grow with time, ordering by id with a created_at filter mostly reads the old end of the clustered index, which works well. If old and new rows are mixed in id order, an index on created_at lets each batch find its rows without scanning, which also keeps the locks taken per batch close to the rows actually deleted.

Should the batched loop run inside one transaction for safety?

No. A single surrounding transaction would hold every batch's locks until the end, re-creating the escalation and log problems. The deletes are safe to commit independently because each removes rows that are old by definition; if the job fails, the next run continues.

7Conclusion

In this answer, we saw that a single 2-million-row DELETE escalates to a table X lock at around 5,000 locks, blocking all writers and, under locking READ COMMITTED, all readers, while filling the log and making cancellation a slow rollback. Deleting in batches of a few thousand rows in clustered key order, each in its own short transaction, keeps locks short and below the threshold, measured through escalation events, API latency and log growth. Partition switching or truncation removes old data almost for free, and LOCK_ESCALATION settings and RCSI help at the margins with trade-offs.

What to say in the interviewAbout 80 seconds aloud

Open with

The single DELETE takes an exclusive lock per row, and once one statement holds about five thousand locks on a table, SQL Server escalates to a table-level X lock.

Then, if they want more

That blocks every insert and update, and with the default locking READ COMMITTED every read too, until the whole delete commits, which is why the API times out. It's also one huge transaction: gigabytes of log that can't be truncated, and if someone cancels it, the rollback takes ages with the table still locked.

I'd rewrite it as a loop deleting a few thousand rows at a time: a CTE with TOP 4000 ordered by the clustered key, delete from the CTE, check @@ROWCOUNT, and pause briefly between batches. Each batch is its own short transaction, stays below the escalation threshold, and if the job dies, the next run continues.

I'd tune the batch size by watching lock_escalation events, batch duration, API p99, log usage and replica lag. Longer term I'd partition the table by date and switch out or truncate old partitions, which is metadata only. LOCK_ESCALATION AUTO and read committed snapshot help too, but they have memory and version store costs, so I'd treat them as extras.

About this answer

Last updated
12 November 2026
Checked
Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
Where the question comes from
Written by Scrivio for practice. It is not taken from an interview.
Report an issue with this answer

Copy the line below and send it to the author with what you found. It carries the address of this page.

Issue with "A nightly SQL Server job deletes 2 million old rows with one DELETE statement, and...": https://scrivio-interview-library.netlify.app/databases/database-locking/0fcfcae976/