Establish a link between data in two tables.
The FOREIGN KEY constraint establishes a referential link between a column in one table and the primary key or a unique key in another table. It enforces referential integrity by ensuring that values in the foreign key column must match an existing value in the referenced table or be NULL. Foreign keys prevent actions that would break the link between tables. You can define ON DELETE and ON UPDATE actions such as CASCADE, SET NULL, or RESTRICT to control what happens when the referenced row is modified or deleted.
| Name | Description | Optional |
|---|---|---|
column |
The column in the current table that references another table. | No |
referenced_table |
The table that contains the referenced primary or unique key. | No |
referenced_column |
The column in the referenced table that is being pointed to. | No |
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
FOREIGN KEY (user_id) REFERENCES users(id)
);
CREATE TABLE order_items (
id INT PRIMARY KEY,
order_id INT,
FOREIGN KEY (order_id) REFERENCES orders(id) ON DELETE CASCADE
);