liveBook · Manning

Foreign key

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

A foreign key is a column or set of columns whose values reference a candidate key in another or the same table.

A foreign key is a column or column set that points to a primary key or unique constraint in another table. It enforces referential integrity: referenced values must exist. For example, Employees.OfficeID can reference Offices.OfficeID instead of repeating office details in every employee row. section 4.1.1

Mistake #13: omitting the constraint because a frontend seems able to protect the data. Applications cannot guarantee integrity as reliably as SQL Server constraints, especially when someone performs an urgent backend correction. section 4.3

The purchase-order transfer trap

PurchaseOrderDetails contains PurchaseOrderNumber but has no foreign key to PurchaseOrderHeaders. Under pressure, an operator runs an update moving details from order 6827 to 6828. If header 6828 does not exist, the details become orphaned. Correct the data first, then add the constraint so future invalid references fail. section 4.3

Use these checks when related tables are designed or repaired:

  • Define the relationship from the dependent table to a primary key or unique constraint. section 4.1.1
  • Prefer normalized tables and document the relationship in an ERD. section 4.4
  • Use a transaction for related inserts, but do not treat transaction handling as a replacement for foreign keys. section 4.3
  • Remember that referenced keys may be natural, artificial, or composite; minimize composite keys where possible. section 4.1.1

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

How deep it goes
Explains key types, referential integrity, operational failure scenarios, corrective SQL, and ERD usage, but not broader constraint internals.
Examples
Uses Employees and Offices, Sales Orders, and PurchaseOrderHeaders with PurchaseOrderDetails to demonstrate valid and invalid references.
What it assumes
Assumes basic tables and rows, while introducing primary keys, unique constraints, natural keys, artificial keys, and composite keys.
What you can do after
Operate/configure SQL Server schemas by identifying missing relationships, repairing invalid data, and adding foreign key constraints.
How it connects
Connects primary keys, unique constraints, normalization, ERDs, natural keys, artificial keys, composite keys, and transactions.

Also explained in

Compare how 18 books explain foreign key →

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.