What is a foreign key in MySQL

A foreign key in MySQL is a field (or a collection of fields) in one table that uniquely identifies a row of another table or the same table. In other words, it is a constraint that ensures the integrity of the data between two tables by linking them together. The concept of foreign keys is fundamental to establishing relationships in relational databases.

Foreign keys help maintain referential integrity between the tables. If a foreign key is defined on a column in a table, then the values in that column can only contain values that are present in the column of the referenced table.

Example

CREATE TABLE customers ( customer_id INT PRIMARY KEY, customer_name VARCHAR(100) ); CREATE TABLE orders ( order_id INT PRIMARY KEY, order_date DATE, customer_id INT, FOREIGN KEY (customer_id) REFERENCES customers(customer_id) );

foreign key MySQL relational databases referential integrity database relationships