A debugging scenario covering unindexed foreign keys that force child-table scans during parent deletes, lock escalation from large deletes, cascades, and untrusted constraints (WITH NOCHECK) that stop the optimiser using them.
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.
"My first suspicion with slow parent deletes is foreign keys without indexes. When you delete a customer, SQL Server has to prove no order still references it. That check is a query against Orders by CustomerId. SQL Server doesn't create an index for a foreign key, so if nobody added one, every deleted customer means scanning Orders. Delete ten thousand customers in one statement and you've got a huge, long-running transaction that holds locks the whole time, and once it passes roughly five thousand locks on a table SQL Server escalates to a table lock. That's when the rest of the application stops.
I'd prove it rather than guess. I'd capture the actual execution plan for one delete: you'll see a clustered index scan on Orders feeding the FK check with logical reads in the hundreds of thousands. While the job runs, sp_WhoIsActive or sys.dm_exec_requests shows the delete as head blocker, with LCK_M waits behind it. For example, at [company] our retention job [deleted inactive customers nightly] and [blocked checkout for several minutes]. I [added indexes on four FK columns and rewrote the job to delete 2,000 rows per transaction], and it [went from 40 minutes with blocking to 3 minutes without].
The WITH NOCHECK detail is the second half. A foreign key or check constraint that was created or re-enabled WITH NOCHECK is marked untrusted. It still checks new writes, but the optimiser can't rely on it, so it can't eliminate redundant joins, and the data may already contain orphans. I find them with sys.foreign_keys where is_not_trusted is 1, clean the bad rows, and re-validate with WITH CHECK CHECK CONSTRAINT in a quiet window. Fast deletes come from indexed foreign keys and small batches; trusted constraints come from validating, not just enabling."
| Cause | Signal | Fix |
|---|---|---|
| Unindexed FK on a child table | Child table scan in the delete plan, high logical reads | Index the FK column(s) |
| One huge delete statement | Lock escalation (table X lock), long blocking | Batches of 1,000β5,000 rows, commit each |
ON DELETE CASCADE chains |
Plan touches many tables, large log growth | Delete children explicitly in batches, or keep cascades shallow |
| Triggers on the parent | Extra statements in the plan | Review trigger logic; set-based |
| Untrusted constraints | is_not_trusted = 1; joins not eliminated |
Clean data, WITH CHECK CHECK CONSTRAINT |
| State | New writes checked? | Optimiser trusts it? |
|---|---|---|
| Enabled and trusted | Yes | Yes |
Enabled, untrusted (WITH NOCHECK) |
Yes | No |
Disabled (NOCHECK CONSTRAINT) |
No | No |
A nightly retention job [in a system you know] deleted [12,000] inactive customers in one statement: [40] minutes, a table lock on Orders and checkout timeouts for [6] minutes. Four FK indexes and 2,000-row batches made it finish in [3] minutes with no blocking; re-validating two untrusted constraints found and fixed [37] orphaned rows.
Checks diagnosis skills for a common production problem and understanding of how SQL Server enforces foreign keys and uses trusted constraints.
Green flags
Red flags
DELETE dbo.Customers WHERE LastActiveAt < @cutoff
β
ββ Clustered Index Delete (Customers)
ββ for each deleted CustomerId:
ββ FK check FK_Orders_Customers β seek or SCAN Orders(CustomerId)
ββ FK check FK_Addresses_Customersβ seek or SCAN Addresses(CustomerId)
ββ Assert: no rows found, else error 547
In the plan the checks appear as joins (often a left semi join) into the child table feeding an Assert operator. With an index on the child FK column each check is a seek of a few pages; without it the optimiser picks a scan (or a hash join over a full scan for many rows).
The delete runs in one transaction. Exclusive locks on deleted rows are held to the end, and the scans read many rows of the child tables. Once a single statement holds about 5,000 locks on one object, SQL Server attempts lock escalation to a table-level lock. A table X lock on Customers or a long-running scan of Orders blocks every checkout that touches those tables. On Azure SQL with RCSI on (the default), readers aren't blocked by the deleter's X locks, but writers still are.
WHILE 1 = 1
BEGIN
DELETE TOP (2000) FROM dbo.Customers WHERE ...;
IF @@ROWCOUNT = 0 BREAK;
END
Each batch commits, releases locks and lets the log be reused (in SIMPLE recovery or after log backups). The batch size stays under the escalation threshold. It needs an index supporting the WHERE so each TOP finds rows quickly instead of rescanning.
ON DELETE CASCADE turns one delete into deletes on every child level, all in one statement. Each level needs an FK index. SQL Server also refuses multiple cascade paths to one table, which is why some designs use triggers instead (worse). For retention jobs, deleting children explicitly from the bottom up in batches is easier to control.
ALTER TABLE Orders WITH NOCHECK ADD CONSTRAINT FK... or ALTER TABLE Orders CHECK CONSTRAINT FK... (which defaults to WITH NOCHECK when re-enabling) leaves is_not_trusted = 1. Effects:
WITH CHECK CHECK CONSTRAINT scans the table and takes a schema modification lock, so on a big table run it in a quiet window after cleaning the data.
SET STATISTICS IO, TIME ON for logical reads per table.sys.dm_exec_requests (blocking_session_id, wait_type), sp_WhoIsActive with @find_block_leaders = 1.blocked process threshold) via Extended Events, and the lock_escalation event.sys.foreign_key_columns.Customers and Orders (1 million orders) without an index on Orders.CustomerId; delete 1,000 customers and capture the actual plan and logical reads.sys.dm_tran_locks for the escalation.CHECK CONSTRAINT and query sys.foreign_keys.is_not_trusted; then fix it with WITH CHECK.Find the cause: unindexed foreign keys and untrusted constraints.
-- Foreign keys whose columns are not the leading columns of any index.
SELECT fk.name AS fk_name,
OBJECT_NAME(fk.parent_object_id) AS child_table,
c.name AS fk_column
FROM sys.foreign_keys AS fk
JOIN sys.foreign_key_columns AS fkc ON fkc.constraint_object_id = fk.object_id
JOIN sys.columns AS c ON c.object_id = fkc.parent_object_id AND c.column_id = fkc.parent_column_id
WHERE NOT EXISTS (
SELECT 1
FROM sys.index_columns AS ic
WHERE ic.object_id = fkc.parent_object_id
AND ic.column_id = fkc.parent_column_id
AND ic.key_ordinal = fkc.constraint_column_id); -- same position in the index key
-- Untrusted foreign keys and check constraints.
SELECT name, OBJECT_NAME(parent_object_id) AS table_name, 'FK' AS kind
FROM sys.foreign_keys WHERE is_not_trusted = 1
UNION ALL
SELECT name, OBJECT_NAME(parent_object_id), 'CHECK'
FROM sys.check_constraints WHERE is_not_trusted = 1;
Fix it: index, batch, re-validate.
CREATE INDEX IX_Orders_CustomerId ON dbo.Orders (CustomerId) WITH (ONLINE = ON);
DECLARE @cutoff datetime2(3) = DATEADD(year, -7, SYSUTCDATETIME());
WHILE 1 = 1
BEGIN
-- Small batches: stay under lock escalation, keep each transaction short.
DELETE TOP (2000) c
FROM dbo.Customers AS c
WHERE c.LastActiveAt < @cutoff
AND NOT EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerId = c.CustomerId);
IF @@ROWCOUNT = 0 BREAK;
WAITFOR DELAY '00:00:00.200'; -- give other sessions room
END;
-- After cleaning orphans: make the constraint trusted again (scans the table).
ALTER TABLE dbo.Orders WITH CHECK CHECK CONSTRAINT FK_Orders_Customers;
The same job from a .NET BackgroundService, one short transaction per batch.
namespace Shop.Jobs;
using Microsoft.Data.SqlClient;
public sealed class CustomerRetentionJob(string connectionString, ILogger<CustomerRetentionJob> logger) : BackgroundService
{
protected override async Task ExecuteAsync(CancellationToken ct)
{
const string sql = """
DELETE TOP (2000) c FROM dbo.Customers AS c
WHERE c.LastActiveAt < DATEADD(year, -7, SYSUTCDATETIME())
AND NOT EXISTS (SELECT 1 FROM dbo.Orders AS o WHERE o.CustomerId = c.CustomerId);
""";
await using var connection = new SqlConnection(connectionString);
await connection.OpenAsync(ct);
int deleted;
do
{
await using var command = new SqlCommand(sql, connection) { CommandTimeout = 30 };
deleted = await command.ExecuteNonQueryAsync(ct); // autocommit: each batch is its own transaction
logger.LogInformation("Deleted {Count} customers", deleted);
await Task.Delay(TimeSpan.FromMilliseconds(200), ct);
} while (deleted > 0 && !ct.IsCancellationRequested);
}
}
sys.foreign_key_columns and index FK columns used by deletes and joins.NOLOCK to other queries to "stop the blocking". Why it is wrong: only affects readers, risks dirty and missing rows, and writers stay blocked. Instead: fix the delete.WITH CHECK.ALTER TABLE ... CHECK CONSTRAINT. Why it is wrong: defaults to WITH NOCHECK, so the constraint stays untrusted. Instead: WITH CHECK CHECK CONSTRAINT.WITH CHECK CHECK CONSTRAINT on a huge table at peak time. Why it is wrong: it scans the table under a schema lock. Instead: clean data first and schedule it.ON DELETE CASCADE chains for retention. Why it is wrong: one statement touches every level at once. Instead: explicit, bottom-up, batched deletes.Slow deletes are almost always a read problem in disguise: the engine is reading child tables to protect integrity. The senior fix keeps the integrity (no disabling FKs) and makes the reads cheap and the transactions short. Untrusted constraints are the quieter cost: they give a false sense of safety and lose optimiser benefits.
| Option | When it fits | Cost | When not to |
|---|---|---|---|
| Index FK columns | Parent deletes, joins via the FK | Write cost per index | FK columns never deleted through or joined (rare) |
| Batched deletes | Retention and purge jobs | Longer total time, needs a supporting index | A few rows |
| Partition switching | Purging whole time ranges from huge tables | Partitioning design, aligned indexes | Row-by-row business rules |
| Soft delete | Need for restore or audit | Filters everywhere, still need purge later | Legal requirement to erase |
Measure with logical reads per batch, blocking time (blocked process report) and lock escalation events.
A constraint is untrusted when is_not_trusted = 1 in sys.foreign_keys or sys.check_constraints. It happens when it is created WITH NOCHECK, or re-enabled with ALTER TABLE ... CHECK CONSTRAINT (which defaults to WITH NOCHECK), typically after a bulk load or a migration that disabled constraints.
Effects: new writes are still checked, but existing rows were never validated, so orphans or invalid values may already be there and reports or joins can return wrong results. The optimiser cannot rely on it, so it loses join elimination and contradiction detection.
Fix: find the violating rows (e.g. LEFT JOIN to the parent where it is NULL), delete, correct or re-parent them, then run ALTER TABLE t WITH CHECK CHECK CONSTRAINT c. It scans the table under a schema lock, so schedule it off-peak on large tables.
Add the constraint WITH NOCHECK so SQL Server enforces it for new writes without scanning existing rows, which avoids a long Sch-M lock. Then find and fix the violating rows in batches, and finally run ALTER TABLE ... WITH CHECK CHECK CONSTRAINT so the constraint becomes trusted (is_not_trusted = 0). Untrusted constraints are still enforced, but the optimiser cannot use them for join elimination or plan simplification, so the last step matters for performance. In EF Core, add the constraint with migrationBuilder.Sql because the scaffolded AddForeignKey always validates.
SQL Server constraints are rules the engine enforces on every write from every client:
Quantity > 0 (NULL passes).I validate in .NET for good error messages, but enforce in the database because other writers exist (scripts, jobs, other services) and race conditions slip past app checks. The cost is a little write overhead and needing to translate constraint errors into friendly responses.
How to tell it (STAR)
**S:** At [company] our nightly retention job deleted old customers and every night checkout timed out for several minutes. **T:** I owned finding the cause without stopping the retention job, which we needed for [privacy compliance]. **A:** I watched it with sp_WhoIsActive, saw the delete as head blocker, and the actual plan showed full scans of Orders under the foreign key check because four FK columns had no index. I added the indexes online, rewrote the job into 2,000-row batches, cleaned [37] orphans and re-validated two untrusted constraints. **R:** The job went from [40] minutes to [3], checkout timeouts at night dropped to zero, and we added a CI check so new FKs always get an index.
Last updated 23 Nov 2026.