A FOREIGN KEY constraint enforces referential integrity between two tables (or within the same table in a self-reference). The column or column group declared as a foreign key must contain values that already exist in the referenced table’s PRIMARY KEY or UNIQUE constraint. The database automatically prevents inserts, updates, or deletes that would break this relationship unless explicitly allowed through ON DELETE or ON UPDATE actions such as CASCADE, SET NULL, SET DEFAULT, or NO ACTION/RESTRICT. FOREIGN KEYs can be created inline within CREATE TABLE or added later with ALTER TABLE. They greatly simplify data consistency by delegating relationship checks to the database engine instead of application code. Caveats: every referenced column must be indexed (implicitly or explicitly); referenced and referencing columns must share compatible data types; and circular or multiple cascade paths are disallowed or limited in some systems.
column_list
- COLUMN One or more columns in the child tablereference_table TABLE
- Table that holds the referenced keyON DELETE action ENUM
(CASCADE) - SET NULL|||SET DEFAULT|||RESTRICT|||NO ACTION (optional)ON UPDATE action ENUM
(CASCADE) - SET NULL|||SET DEFAULT|||RESTRICT|||NO ACTION (optional)PRIMARY KEY, UNIQUE, REFERENCES, ON DELETE, ON UPDATE, CASCADE, CHECK, INDEX
SQL-92 standard
All matching child rows are automatically removed along with the parent, preventing orphaned data.
Many databases allow disabling or deferring constraints within a transaction. Syntax varies (e.g., SET CONSTRAINTS ALL DEFERRED in PostgreSQL).
Yes. You can reference a composite PRIMARY KEY or UNIQUE index by listing columns in the same order on both sides of the constraint.
Some systems create it automatically (MySQL InnoDB, SQL Server). Others require you to create an index manually on the child column for performance.