Referential integrity in SQL Server: keys and orphan rows

Referential integrity means every foreign key value points at a row that exists. How SQL Server enforces it, and how to find the orphan rows that slip past.

What is referential integrity?

Referential integrity is the rule that every foreign key value points at a row that exists. An order that says “customer 1” needs a customer 1, and an order line that says “product 10” needs a product 10. A row whose foreign key points at nothing is an orphan. Orphans don’t raise errors when you read them; they just fall out of joins, so a sales report that joins order lines to products comes up short and nobody is told.

Entity integrity is the primary key’s half: every row has a unique, non-NULL key. Referential integrity is the foreign key’s half.

In SQL Server, a foreign key constraint enforces the rule. Here is a small shop: customers place orders, each order has lines, and each line sells a product. The online shopping system template is the full store, with carts, payments and reviews.

CREATE TABLE dbo.Customer (
  CustomerId int NOT NULL CONSTRAINT PK_Customer PRIMARY KEY,
  Email      nvarchar(254) NOT NULL,
  FullName   nvarchar(100) NOT NULL
);
CREATE TABLE dbo.Product (
  ProductId int NOT NULL CONSTRAINT PK_Product PRIMARY KEY,
  Sku       varchar(20)   NOT NULL,
  Name      nvarchar(100) NOT NULL,
  Price     decimal(9, 2) NOT NULL
);
CREATE TABLE dbo.[Order] (
  OrderId    int  NOT NULL CONSTRAINT PK_Order PRIMARY KEY,
  CustomerId int  NOT NULL,
  OrderedOn  date NOT NULL,
  CONSTRAINT FK_Order_Customer_CustomerId
    FOREIGN KEY (CustomerId)
    REFERENCES dbo.Customer (CustomerId)
    ON DELETE CASCADE
);
CREATE TABLE dbo.OrderLine (
  OrderId    int           NOT NULL,
  LineNumber smallint      NOT NULL,
  ProductId  int           NOT NULL,
  Quantity   int           NOT NULL,
  UnitPrice  decimal(9, 2) NOT NULL,
  CONSTRAINT PK_OrderLine PRIMARY KEY (OrderId, LineNumber),
  CONSTRAINT FK_OrderLine_Order_OrderId
    FOREIGN KEY (OrderId)
    REFERENCES dbo.[Order] (OrderId)
    ON DELETE CASCADE,
  CONSTRAINT FK_OrderLine_Product_ProductId
    FOREIGN KEY (ProductId)
    REFERENCES dbo.Product (ProductId)
);
dbo.Customer, dbo.Order, dbo.OrderLine and dbo.Product; lines from Customer to Order, from Order to OrderLine and from Product to OrderLine.
Three relationships, three foreign keys: each line is a constraint SQL Server checks on every insert, update and delete.

With these keys in place, an order line can’t name a missing product, and a product that is still on an order line can’t be deleted. Both are refused with Msg 547, which primary key vs foreign key walks through. The order line’s key is the order plus a line number, a composite key, which is why its line to dbo.Order is solid.

The rest of this post is about what deletes do to child rows, how orphans get in anyway, and how to find them.

What a delete does to the rows below it

The two ON DELETE CASCADE clauses decide what deleting a customer means. Ana, customer 1, has order 100 with two lines; Ben, customer 2, has order 101 with one:

INSERT INTO dbo.Customer (CustomerId, Email, FullName)
VALUES (1, N'ana@example.com', N'Ana Silva'),
       (2, N'ben@example.com', N'Ben Okafor');
INSERT INTO dbo.Product (ProductId, Sku, Name, Price)
VALUES (10, 'MUG-01', N'Mug', 9.50),
       (11, 'TEE-02', N'T-shirt', 18.00);
INSERT INTO dbo.[Order] (OrderId, CustomerId, OrderedOn)
VALUES (100, 1, '2026-05-04'),
       (101, 2, '2026-05-06');
INSERT INTO dbo.OrderLine
  (OrderId, LineNumber, ProductId, Quantity, UnitPrice)
VALUES (100, 1, 10, 2, 9.50),
       (100, 2, 11, 1, 18.00),
       (101, 1, 10, 1, 9.50);
DELETE FROM dbo.Customer WHERE CustomerId = 1;
DELETE FROM dbo.Product WHERE ProductId = 10;

Deleting Ana takes her order and its two lines with her, in the same statement. Deleting the mug fails with Msg 547: order 101 still sells it, and FK_OrderLine_Product_ProductId has no ON DELETE clause, so it is NO ACTION. Either way no orphan is left behind, because the children go with their parent or the parent stays. SET NULL and SET DEFAULT, the other two actions, keep the children and change their foreign key instead. Which keys should cascade, what each action needs from its column, and why two cascade paths into one table fail with Msg 1785 are in ON DELETE CASCADE.

What WITH NOCHECK does to a foreign key

Orphans get past a foreign key one way: the key wasn’t checking when they arrived. A bulk load drops the key, loads the rows, one of them an order line for product 99, and puts the key back. Adding a key checks the existing rows by default, so the usual ALTER TABLE ... ADD CONSTRAINT fails with Msg 547, “The ALTER TABLE statement conflicted with the FOREIGN KEY constraint”, and stops the batch. So the load script says WITH NOCHECK:

ALTER TABLE dbo.OrderLine
  DROP CONSTRAINT FK_OrderLine_Product_ProductId;
INSERT INTO dbo.OrderLine
  (OrderId, LineNumber, ProductId, Quantity, UnitPrice)
VALUES (101, 2, 99, 1, 4.00);
ALTER TABLE dbo.OrderLine WITH NOCHECK ADD
  CONSTRAINT FK_OrderLine_Product_ProductId
    FOREIGN KEY (ProductId)
    REFERENCES dbo.Product (ProductId);
dbo.Customer, dbo.Order, dbo.OrderLine and dbo.Product; lines from Customer to Order, from Order to OrderLine and from Product to OrderLine.
The relationship is back, while order 101's second line sells product 99, which dbo.Product doesn't have.

The key checks every insert and update from now on. The rows already there were never checked, so SQL Server marks the key untrusted: is_not_trusted is 1 in sys.foreign_keys. Two things follow. The orphan stays, and the optimizer stops relying on the key, as the ALTER TABLE reference says. With the key trusted, a query that joins dbo.OrderLine to dbo.Product but reads only order line columns never touches dbo.Product, because every line is known to have its product. With the key untrusted, the plan reads both tables.

Disabling a key ends the same way. NOCHECK CONSTRAINT turns it off, is_disabled 1. CHECK CONSTRAINT turns it back on but leaves it untrusted, because re-enabling defaults to not checking the rows. Only WITH CHECK CHECK CONSTRAINT, the word twice, checks the rows and trusts the key again.

How to find orphan rows

Start with the keys SQL Server doesn’t trust, then look for the rows each one would reject:

SELECT fk.name, fk.is_disabled, fk.is_not_trusted
FROM sys.foreign_keys AS fk
WHERE fk.parent_object_id = OBJECT_ID(N'dbo.OrderLine');

SELECT ol.OrderId, ol.LineNumber, ol.ProductId
FROM dbo.OrderLine AS ol
WHERE NOT EXISTS (
  SELECT 1 FROM dbo.Product AS p
  WHERE p.ProductId = ol.ProductId
);

DBCC CHECKCONSTRAINTS (N'dbo.OrderLine');

The first query lists FK_OrderLine_Product_ProductId as untrusted. The second finds its orphan, line 2 of order 101 with product 99. That is the pattern for any foreign key: the child rows with no matching parent. On a nullable foreign key, add IS NOT NULL on the column, because a NULL is allowed and isn’t an orphan.

DBCC CHECKCONSTRAINTS does it for every foreign key and check constraint of a table, one row per violation: the table, the constraint and a condition, here [ProductId] = '99'. It checks enabled constraints only; a disabled one needs WITH ALL_CONSTRAINTS.

Then fix the data, by adding the missing product or deleting the line, and trust the key again with ALTER TABLE dbo.OrderLine WITH CHECK CHECK CONSTRAINT FK_OrderLine_Product_ProductId. While an orphan is left, it fails with Msg 547 and ends the batch, so it doubles as the test that none is.

How ERDsmith helps

Product 99’s order line got in through a key that wasn’t checking, and the query that found it needed the key’s columns and its parent. Data checks like that start from the declared keys, so the keys belong in the design, where a relationship nobody declared shows as a missing line. In ERDsmith each line is a foreign key:

  • Its child columns are one per column of the parent’s key, in key order, which is the join the orphan query makes.
  • It is optional exactly when all its columns allow NULL, the case where that query adds IS NOT NULL.
  • It starts with the project’s default actions on delete and on update, NO ACTION until someone sets them: the action that refuses a delete which would leave orphans behind.