Understanding Foreign Keys in MySQL
A foreign key is a column or a set of columns in one table that refers to the PRIMARY KEY (or UNIQUE key) of another table. It establishes a relationship between the two tables and ensures that the data remains consistent.
They enforce referential integrity, ensuring relationships between tables remain valid.
They prevent invalid data — e.g., you cannot insert an order for a non-existing customer.
They maintain consistency across related tables.
They enable cascading actions (ON DELETE and ON UPDATE).
Parent row must exist before child rows can reference it.
Child rows cannot refer to non-existing parent rows.
Optional cascading actions such as deleting or updating related rows.
In this example, each order must be linked to a valid customer. MySQL prevents inserting an order with a customer_id that does not exist in the customers table.