Foreign Key
A foreign key is a column that links one table to another by pointing to the primary key of a different table. It is how relationships between tables are enforced.
SQL
For example, an 'orders' table might have a customer_id column that is a foreign key referencing the 'id' in the 'customers' table. This ties each order to a real customer.
Foreign keys protect data integrity: the database can reject an order whose customer_id doesn't match any existing customer, preventing 'orphaned' records.
Syntax
FOREIGN KEY (column) REFERENCES other_table(column)Examples
SQL
CREATE TABLE orders (
id INT PRIMARY KEY,
customer_id INT,
FOREIGN KEY (customer_id) REFERENCES customers(id)
);Output:
Orders now reference valid customers only.