SQLMentor // glossary

Foreign Key

A foreign key is a column whose values must match a primary (or unique) key in another table. It enforces referential integrity — you cannot reference a row that does not exist.

Foreign keys are how relational databases link tables together. If employees.department_id is a foreign key to departments.department_id, the database blocks any employee row whose department does not exist, and can optionally cascade deletes or updates.

A NULL foreign key is allowed (meaning "no relationship yet") unless the column is also declared NOT NULL.

Example

ALTER TABLE employees
  ADD CONSTRAINT fk_dept
  FOREIGN KEY (department_id)
  REFERENCES departments (department_id);