What is a foreign key?
BeginnerConceptMySQL
Answer
Short answer
A foreign key is a column in one table that points to the primary key of another table, creating a relationship. The database then guarantees the reference is valid — you can't insert an order for a customer who doesn't exist.
Example
CREATE TABLE orders (
id INT AUTO_INCREMENT PRIMARY KEY,
customer_id INT NOT NULL,
total DECIMAL(10,2),
FOREIGN KEY (customer_id) REFERENCES customers(id) ON DELETE RESTRICT
);
INSERT INTO orders (customer_id, total) VALUES (999, 100);
-- ERROR 1452: Cannot add or update a child row: a foreign key constraint fails
ON DELETE options
| Option | When the customer is deleted |
|---|---|
RESTRICT (default) |
Delete is blocked while orders exist |
CASCADE |
Their orders are deleted too |
SET NULL |
customer_id becomes NULL |
DevOps relevance
Foreign keys affect restore order and bulk loads: restoring tables in the wrong order fails. mysqldump handles it by writing SET FOREIGN_KEY_CHECKS=0 at the top of the dump.
What to say in the interview
"A foreign key references another table's primary key and enforces referential integrity. ON DELETE rules control what happens to child rows, and it's why dumps disable FK checks during restore."
More on MySQL
How do you set up MySQL and log in to it?BeginnerHow do you create a database, a table and see data in MySQL?BeginnerHow do you create a MySQL user for an application and give it permissions?BeginnerHow do you back up and restore a MySQL database?BeginnerWhat is a relational database?BeginnerWhat is the difference between a database, a table, a row and a column?Beginner