Purpose of FOREIGN KEY in Maintaining Referential Integrity
A FOREIGN KEY ensures that values in one table correspond to valid entries in another table. Its purpose is to maintain referential integrity — meaning relationships between tables always remain valid and consistent.
Prevents inserting a child row that references a non-existing parent row.
Prevents deleting a parent row if child rows still depend on it (unless cascading is defined).
Ensures updates to a referenced key are handled safely (restricted or cascaded).
Guarantees that relationships between tables remain logically correct.
Avoids orphan records in child tables.
Keeps data consistent across related tables.
Provides structured, reliable, and predictable relationships in the database.
Supports cleaner database design with safe relational links.
With a FOREIGN KEY in place, MySQL actively enforces that any referenced data must be valid, preventing broken or inconsistent relationships.