A foreign key is a column that points at the primary key of another table, and the constraint keeps that link valid. Every value in it must match an existing row in the other table, and the other table cannot lose a row that something still points at.
In the example database, Invoices.ProductionID points at Productions.ProductionID. Invoices is called the child table and Productions the parent.
Declaring one
Section titled “Declaring one”CREATE TABLE Invoices ( InvoiceID int PRIMARY KEY, ProductionID int NOT NULL, Supplier varchar(100) NOT NULL, Amount decimal(10, 2) NOT NULL, CONSTRAINT FK_Invoices_Productions FOREIGN KEY (ProductionID) REFERENCES Productions (ProductionID));What it prevents
Section titled “What it prevents”With the constraint in place, the database refuses two kinds of change:
- An invoice for a production that does not exist. Recording an invoice against production 9 fails, so no invoice can belong to nothing.
- Deleting a production that still has invoices. Deleting The Lantern Keepers fails while its two invoices point at it, so no invoice is left orphaned.
Without the constraint, both changes would succeed silently, and the mistakes would surface later as invoices that vanish from joined reports.
Choosing what happens on delete
Section titled “Choosing what happens on delete”The refusal is the default. A foreign key can instead say what should happen to the child rows when their parent goes:
ON DELETE CASCADEdeletes the child rows along with the parent.ON DELETE SET NULLkeeps the child rows and empties their foreign key.
CONSTRAINT FK_Invoices_Productions FOREIGN KEY (ProductionID) REFERENCES Productions (ProductionID) ON DELETE CASCADEChoose cascade with care. Deleting one production would then delete its invoices too, which is rarely what accounts records should do.
On an existing table
Section titled “On an existing table”ALTER TABLE InvoicesADD CONSTRAINT FK_Invoices_Productions FOREIGN KEY (ProductionID) REFERENCES Productions (ProductionID);The constraint is refused if an existing invoice already points at a missing production. Remove it by name with ALTER TABLE Invoices DROP CONSTRAINT FK_Invoices_Productions;, or in MySQL with DROP FOREIGN KEY in place of DROP CONSTRAINT.