Question №31
Remaining:
What is a FOREIGN KEY and how does it ensure data integrity?
Sample Answer
Show Answer by Default
A FOREIGN KEY is a constraint that establishes a relationship between a column or set of columns in one table and a column or columns in another table (typically a primary key).
It ensures referential integrity by guaranteeing that values in the foreign key column correspond to existing values in the related table.
How data integrity is ensured:
-
Prevents insertion of invalid data It is impossible to insert a value into the foreign key column if that value does not exist in the related table.
-
Prevents deletion of related records It is impossible to delete a record from the parent table if records in the child table reference it, unless additional actions are taken.
Example of a foreign key:
MySQL 8.1CREATE TABLE Employees ( EmployeeID INT PRIMARY KEY, Name VARCHAR(100), DepartmentID INT, FOREIGN KEY (DepartmentID) REFERENCES Departments(DepartmentID) );