What is a Foreign Key?
Foreign Keys and Referential Integrity
A Foreign Key establishes a parent-child relationship between tables, guaranteeing that relationships remain valid across all operations.
Referential Actions Table
| Action | Behavior when Parent is Deleted / Updated |
|---|---|
CASCADE |
Automatically deletes or updates referencing child rows |
SET NULL |
Sets the child foreign key column value to NULL |
RESTRICT |
Rejects parent deletion if any child records reference it |
NO ACTION |
Raises an error if foreign key constraints are violated |
SQL Declaration Example
CREATE TABLE orders (
id INT PRIMARY KEY,
user_id INT,
total NUMERIC(10,2),
CONSTRAINT fk_user FOREIGN KEY (user_id)
REFERENCES users(id)
ON DELETE CASCADE
ON UPDATE CASCADE
);