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

πŸ“š Interview question

Deleting old customers from a SQL Server database has become very slow, and while the delete job runs other sessions are blocked. The tables have foreign keys, some created WITH NOCHECK years ago. How do you diagnose and fix it?

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.

Senior Debugging Advanced blocking debugging foreign-keys lock-escalation sql-server untrusted-constraints

🎯 Key points

  • A parent delete checks every child table for references
  • Unindexed FK column means a child-table scan per delete
  • How the delete is written matters too: one huge statement holds locks for its whole run
  • Large single-statement deletes escalate to a table lock (~5,000 locks)
  • Find it in the actual plan: scan under the FK check, high logical reads
  • Find blockers with sys.dm_exec_requests, sp_WhoIsActive, blocked process report
  • Fix: index FK columns, delete in small batches, keep statistics current after big purges
  • Untrusted constraints (is_not_trusted = 1): clean orphans, then WITH CHECK CHECK CONSTRAINT

⏱ 30-second 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.

πŸ—£ Full answer (senior)

How I would answer this in an interview

"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."


Causes and their signals

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

Untrusted vs disabled

State New writes checked? Optimiser trusts it?
Enabled and trusted Yes Yes
Enabled, untrusted (WITH NOCHECK) Yes No
Disabled (NOCHECK CONSTRAINT) No No

Production example

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.

πŸ” What the interviewer is checking

Checks diagnosis skills for a common production problem and understanding of how SQL Server enforces foreign keys and uses trusted constraints.

Green flags

  • Names unindexed FKs as the first suspect and explains why
  • Uses actual plans and blocking DMVs to prove it
  • Mentions lock escalation and batching
  • Knows what WITH NOCHECK does and how to re-validate

Red flags

  • Disables constraints or uses NOLOCK as the fix
  • Restarts the job or the server without diagnosis
  • Does not know FKs are not auto-indexed

πŸ“š Learn in depth

1. What a parent delete actually does

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).

2. Why it blocks others

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.

3. Batching

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.

4. Cascades

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.

5. Untrusted constraints

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:

  • The optimiser cannot assume referential integrity, so join elimination stops working (a view joining Orders to Customers always reads Customers).
  • Check constraints cannot be used for contradiction detection or partitioned view elimination.
  • Orphaned or invalid rows may already exist.

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.

6. Tools

  • Actual execution plan (SSMS, Azure Data Studio, or Query Store's plan view).
  • 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 report (blocked process threshold) via Extended Events, and the lock_escalation event.
  • A missing-FK-index query over sys.foreign_key_columns.

Try it yourself

  1. Create Customers and Orders (1 million orders) without an index on Orders.CustomerId; delete 1,000 customers and capture the actual plan and logical reads.
  2. Add the index and repeat.
  3. In a second session, try to insert an order while a 20,000-row delete runs; watch sys.dm_tran_locks for the escalation.
  4. Rewrite the delete as a batched loop and compare blocking.
  5. Re-enable a constraint with CHECK CONSTRAINT and query sys.foreign_keys.is_not_trusted; then fix it with WITH CHECK.

πŸ’» Code

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);
    }
}

⚠ Common mistakes

  • Mistake: Assuming foreign keys are indexed automatically. Why it is wrong: SQL Server never creates that index. Instead: audit with sys.foreign_key_columns and index FK columns used by deletes and joins.
  • Mistake: Deleting hundreds of thousands of rows in one statement. Why it is wrong: long transaction, lock escalation, log growth. Instead: batched deletes with short transactions.
  • Mistake: Adding 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.
  • Mistake: Disabling the foreign keys to speed up the delete. Why it is wrong: allows orphans and leaves constraints untrusted. Instead: index and batch; if disabled for a bulk job, re-enable WITH CHECK.
  • Mistake: Re-enabling with ALTER TABLE ... CHECK CONSTRAINT. Why it is wrong: defaults to WITH NOCHECK, so the constraint stays untrusted. Instead: WITH CHECK CHECK CONSTRAINT.
  • Mistake: Running 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.
  • Mistake: Relying on deep ON DELETE CASCADE chains for retention. Why it is wrong: one statement touches every level at once. Instead: explicit, bottom-up, batched deletes.

πŸ› Senior insight: trade-offs

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.

πŸ”— Follow-ups the interviewer may ask

  1. When: Candidate mentions WITH NOCHECK or disabling constraints. Why: Checks depth on untrusted constraints.
    How to answer

    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.

  2. When: Candidate proposes adding or re-validating constraints on a large live table. Why: Checks how to do it without blocking writes.
    How to answer

    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.

  3. When: Candidate is unsure what a foreign key checks. Why: Checks the basics of constraint enforcement.
    How to answer

    SQL Server constraints are rules the engine enforces on every write from every client:

    • PRIMARY KEY: unique and NOT NULL; creates a clustered index by default.
    • UNIQUE: no duplicates; backed by a unique index (allows one NULL).
    • FOREIGN KEY: the value must exist in the parent; blocks orphans; does not create an index for you.
    • CHECK: a row-level condition such as Quantity > 0 (NULL passes).
    • DEFAULT and NOT NULL: a value always exists.

    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.

πŸ›  Real-world problems: how you handle them

Nightly customer retention job blocks checkout
Situation
A retail platform on Azure SQL [tier] had a nightly job deleting customers inactive for seven years [to meet the retention policy under the Privacy Act 1988 APP 11]. Orders had [20 million] rows; several child tables referenced Customers.
Signals
Checkout errors and timeouts every night around [01:00]; Application Insights showed SQL dependency timeouts on `INSERT Orders`; the job's runtime had grown to [40] minutes.
Investigation
sp_WhoIsActive during the job showed the delete as head blocker with [60] sessions waiting on LCK_M_IX. The actual plan of one delete showed clustered index scans on `Orders` and `Addresses` feeding the FK Assert, with [1.2 million] logical reads. Extended Events captured a `lock_escalation` event on `Customers`. The FK audit query found [4] unindexed FK columns and `sys.foreign_keys` showed [2] untrusted constraints.
Resolution
Immediate: paused the job and moved it to a quieter window. Real fix: created the four FK indexes online, rewrote the job to delete 2,000 customers per transaction with a short delay, cleaned [37] orphaned rows and re-validated the untrusted constraints with `WITH CHECK CHECK CONSTRAINT`.
Prevention
CI check for FK indexes on new migrations; alert on blocking longer than 30 s via the blocked process report; a weekly check for untrusted constraints; runbook for purge jobs (batched, idempotent, resumable).

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.

↩ Usually asked after

More in Database Design

Last updated 23 Nov 2026.

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me