🗄️ Fix a Query Plan Silently Ignoring a Foreign Key for Join Elimination Because the Constraint Was Added WITH NOCHECK and Is Marked Untrusted
SQL Server’s optimizer can use a trusted foreign key constraint to simplify certain queries — for example, eliminating a join to a referenced table entirely when the query doesn’t actually select any of that table’s columns, since a trusted FK guarantees every referencing row really does have a matching parent. A foreign key created or re-enabled with WITH NOCHECK skips validating the existing data at creation time, and SQL Server marks that constraint as not trusted (is_not_trusted = 1 in sys.foreign_keys) to reflect that it can’t actually guarantee referential integrity for rows that existed before the check was skipped. The optimizer treats an untrusted constraint as if it isn’t there at all for these simplifications, which means a query that could have skipped an entire join keeps performing it, with no error and nothing in the query’s results different — only the plan, and the performance, quietly worse than it should be.
🔎 The Problem
SELECT o.OrderId, o.OrderDate FROM Orders o JOIN Customers c ON c.CustomerId = o.CustomerId; -- If the FK Orders.CustomerId -> Customers.CustomerId is trusted, -- the optimizer can prove every Orders row already has a matching -- Customers row and drop the join entirely, since no Customers -- column is actually selected. SELECT * FROM sys.foreign_keys WHERE name = 'FK_Orders_Customers'; -- is_not_trusted = 1 <- added WITH NOCHECK (or never revalidated); -- the optimizer can't rely on it, so the join elimination never happens.
✅ The Fix
- Find untrusted constraints with SELECT name FROM sys.foreign_keys WHERE is_not_trusted = 1, which lists every FK the optimizer currently can’t rely on for these kinds of simplifications.
- Revalidate a constraint you believe is actually fine with ALTER TABLE Orders WITH CHECK CHECK CONSTRAINT FK_Orders_Customers, which scans the existing data once and flips the constraint back to trusted if everything actually matches.
- If the existing data genuinely has violations that WITH NOCHECK was used to paper over, fix those rows first — trusting a constraint that doesn’t actually hold is worse than an untrusted one, since it would let the optimizer make incorrect assumptions about data that doesn’t support them.
🚨 Why This Is Dangerous
- An untrusted constraint affects more than just this one join-elimination case — it’s a standing signal to the optimizer that your own data might not actually satisfy a relationship your schema claims to enforce, which can quietly rule out other, unrelated optimizations across the database that also would have relied on it.
A foreign key that exists but isn’t trusted gives you the schema documentation without the optimizer benefit — it looks enforced, but SQL Server knows better than to actually rely on it.
