SQLite FOREIGN KEY Constraint
FOREIGN KEY
A foreign key is a column that refers to the primary key of another table. The constraint makes sure that the value exists in the other table.
In Northwind, the CustomerID column in the Orders table refers to the Customers table:
CREATE TABLE Orders (
OrderID INTEGER PRIMARY KEY,
CustomerID INTEGER REFERENCES Customers(CustomerID),
...
);
Turn On Foreign Keys
SQLite does not check foreign keys by default. You must turn the check on in every connection:
PRAGMA foreign_keys = ON;
Now SQLite refuses to delete a customer that has orders:
Create a Foreign Key
This example creates two tables, where each player must belong to a team:
Example
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS Teams (
TeamID INTEGER PRIMARY KEY,
TeamName TEXT
);
CREATE TABLE IF NOT EXISTS Players (
PlayerID INTEGER PRIMARY KEY,
Name TEXT,
TeamID INTEGER REFERENCES Teams(TeamID)
);
INSERT OR IGNORE INTO Teams VALUES
(1, 'Red'), (2, 'Blue');
INSERT INTO Players (Name, TeamID)
VALUES ('Emil', 1), ('Nora', 2);
SELECT * FROM Players;
Try it Yourself »
You can also write the foreign key as a table constraint:
FOREIGN KEY (TeamID) REFERENCES Teams(TeamID)
Breaking the Rule
There is no team with TeamID 3, so this insert gives an error:
Example
PRAGMA foreign_keys = ON;
CREATE TABLE IF NOT EXISTS Teams (
TeamID INTEGER PRIMARY KEY,
TeamName TEXT
);
CREATE TABLE IF NOT EXISTS Players (
PlayerID INTEGER PRIMARY KEY,
Name TEXT,
TeamID INTEGER REFERENCES Teams(TeamID)
);
INSERT INTO Players (Name, TeamID)
VALUES ('Linus', 3);
Try it Yourself »
ON DELETE CASCADE
ON DELETE CASCADE deletes the related records too. If a team is deleted, its players are deleted with it:
TeamID INTEGER REFERENCES Teams(TeamID)
ON DELETE CASCADE