What is a foreign key?
Why Interviewers Ask This
Interviewers use this question to quickly assess whether a candidate has the foundational knowledge required for MySQL / SQL development. It reveals whether you understand the building blocks that more complex concepts rely on.
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.
Pro Tip
Demonstrate both theoretical understanding and practical experience. Say what it is, then give an example of how you actually used it in a MySQL / SQL codebase.