Skip to content

SQL FOREIGN KEY Constraint

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.

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)
);

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.

The refusal is the default. A foreign key can instead say what should happen to the child rows when their parent goes:

  • ON DELETE CASCADE deletes the child rows along with the parent.
  • ON DELETE SET NULL keeps the child rows and empties their foreign key.
CONSTRAINT FK_Invoices_Productions
FOREIGN KEY (ProductionID) REFERENCES Productions (ProductionID)
ON DELETE CASCADE

Choose cascade with care. Deleting one production would then delete its invoices too, which is rarely what accounts records should do.

ALTER TABLE Invoices
ADD 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.