Before continuing: This entry is part of the constraints and keys guide. If you are new to the topic, start with CREATE TABLE.
FOREIGN KEY example
CREATE TABLE customers_demo (
id INTEGER PRIMARY KEY,
name VARCHAR(100) NOT NULL
);
CREATE TABLE orders_demo (
id INTEGER PRIMARY KEY,
customer_id INTEGER NOT NULL,
total DECIMAL(10, 2) NOT NULL,
FOREIGN KEY (customer_id) REFERENCES customers_demo(id)
);The child column and the referenced column must represent the same data and use compatible types. Their names can differ; what matters is the declared relationship.
How FOREIGN KEY is used
The child column and the referenced column must represent the same data and use compatible types. Their names can differ; what matters is the declared relationship.
What changes from case to case
You can declare actions for when the referenced key is deleted or updated:
NO ACTION: does not fix the child rows automatically; if the relationship is still invalid when the constraint is checked, the operation fails. On engines that allow deferred checking, there may be room inside the transaction to restore integrity before that point.RESTRICT: rejects the delete or update of a referenced row straight away. PostgreSQL and SQLite document that this check is not deferred in the same way asNO ACTION.CASCADE: carries the delete or change through to the child rows.SET NULL: keeps the child row and clears its reference, provided the column acceptsNULL.
Do not choose CASCADE for convenience. Use it only when deleting the parent record really should delete the child records under the business rules. A transaction and a backup are still essential for destructive operations.
Common mix-ups with FOREIGN KEY
Confusing a relationship with uniqueness
customer_id INTEGER UNIQUE
REFERENCES customers_demo(id)UNIQUE would allow at most one order per customer. In a one-to-many relationship, the foreign key value must repeat in as many child rows as needed.