What is a foreign key?

Answer

A foreign key is a column in one table that references the primary key of another table, establishing a relationship between the two tables and enforcing referential integrity. Example: an orders table has a user_id column that is a foreign key referencing users.id — every order must belong to a valid user. Declaration: user_id INT, FOREIGN KEY (user_id) REFERENCES users(id). Referential integrity rules control what happens when the referenced row is updated or deleted — configured with ON DELETE and ON UPDATE actions: CASCADE — automatically delete/update child rows when parent is deleted/updated; SET NULL — set the foreign key to NULL; RESTRICT — prevent deletion of parent if child rows exist (default); SET DEFAULT — set to default value. Foreign keys enable JOINs between tables and prevent orphan records (orders without a valid user). In MySQL, foreign key constraints require both tables to use the InnoDB storage engine.