liveBook · Manning

Referential integrity

As explained in 100 SQL Server Mistakes and How to Avoid Them

Referential integrity is the property that relationships between tables contain only references to existing valid key values.

Referential integrity ensures that relationships between tables contain only references to existing key values. A foreign key in Employees can point to an existing OfficeID in Offices, preventing invalid office references. section 4.1.1

Mistake #13: trusting application logic instead of enforcing relationships in the database.

  • Changing a detail row’s PurchaseOrderNumber to 6828 may seem reasonable when replacing order 6827, but it creates orphaned details if header 6828 does not exist. section 4.3
  • A later inner join then returns neither purchase order, hiding the affected details from ordinary queries. section 4.3
  • Application safeguards cannot catch every mistake made outside the application, so related tables should have primary and foreign key constraints. section 4.3

MagicChoc purchase orders

Correct existing values before adding the constraint; otherwise constraint creation fails. Then enforce the relationship with: ALTER TABLE dbo.PurchaseOrderDetails ADD CONSTRAINT FK_PurchaseOrderDetails_PurchaseOrderHeaders FOREIGN KEY (PurchaseOrderNumber) REFERENCES dbo.PurchaseOrderHeaders(PurchaseOrderNumber);

How 100 SQL Server Mistakes and How to Avoid Them covers it

How deep it goes
Defines the property, demonstrates its failure, and shows repair and constraint-creation SQL without descending into constraint internals.
Examples
Uses Employees and Offices, plus MagicChoc purchase-order headers and details, to demonstrate valid and invalid references.
What it assumes
Assumes basic tables and keys, while introducing foreign keys, natural keys, artificial keys, and composite keys.
What you can do after
Operate/configure relational schemas by repairing invalid values and adding foreign key constraints with T-SQL.
How it connects
Connects foreign keys with primary keys, table relationships, joins, schema design, and entity-relationship diagrams.

Also explained in

Compare how 4 books explain referential integrity →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 SQL Server Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.