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

📚 Interview question

How do you add a foreign key or CHECK constraint to a large, live SQL Server table without blocking writes or failing on existing bad data?

Senior Theory Advanced

🎯 Key points

  • WITH NOCHECK skips validating existing rows
  • New inserts and updates are still checked
  • Clean existing bad data in batches
  • WITH CHECK CHECK CONSTRAINT makes it trusted
  • Untrusted constraints block optimiser simplifications
  • Use migrationBuilder.Sql because AddForeignKey validates

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

🔍 What the interviewer is checking

Checks WITH NOCHECK, data clean-up and validating constraints later

↩ Usually asked after

More in Production EF

Last updated 23 Nov 2026.

🌐 Sangam's Webring

⏪ Previous 🏠 Main Next ⏩
💬 Chat with me