Careeroza
FOREIGN KEY
SQL FOREIGN KEY Constraint
A FOREIGN KEY is a column in one table that refers to the PRIMARY KEY of another table. The table with the foreign key is the child; the referenced table is the parent.
In the demo database, Orders.CustomerID is a foreign key to Customers.CustomerID. The constraint prevents orders for customers that do not exist, and prevents deleting a customer who still has orders.
CREATE TABLE Orders (
OrderID INT PRIMARY KEY,
CustomerID INT,
OrderDate DATE,
CONSTRAINT FK_Orders_Customers FOREIGN KEY (CustomerID)
REFERENCES Customers(CustomerID)
);Referential Actions
You decide what happens to child rows when the parent row is deleted or its key is updated:
| Action | Effect on child rows |
|---|---|
NO ACTION / RESTRICT (default) | the delete/update is rejected |
CASCADE | child rows are deleted/updated too |
SET NULL | the foreign key in the child becomes NULL |
SET DEFAULT | the foreign key gets its default value |
CREATE TABLE OrderDetails (
OrderDetailID INT PRIMARY KEY,
OrderID INT REFERENCES Orders(OrderID) ON DELETE CASCADE,
ProductID INT REFERENCES Products(ProductID) ON DELETE RESTRICT,
Quantity INT
);Seeing It Work
Example
With ON DELETE CASCADE, deleting an order also deletes its lines. (SQLite needs PRAGMA foreign_keys = ON.)
PRAGMA foreign_keys = ON;
CREATE TABLE Parent (ID INTEGER PRIMARY KEY, Name TEXT);
CREATE TABLE Child (
ID INTEGER PRIMARY KEY,
ParentID INTEGER REFERENCES Parent(ID) ON DELETE CASCADE
);
INSERT INTO Parent VALUES (1, 'Order A'), (2, 'Order B');
INSERT INTO Child VALUES (10, 1), (11, 1), (12, 2);
DELETE FROM Parent WHERE ID = 1;
SELECT * FROM Child;Result: 1 row
| ID | ParentID |
|---|---|
| 12 | 2 |