sql · level 2 · unit 6 · lesson 4
- meet it
- guess first
- your turn
- fix it
- nailed it
Tap a green word if you get lost.
meet it
makes a foreign key point at a real row.
So far, nothing stopped a pet having owner_id 99 when no owner 99 exists. That broken link would quietly vanish from every JOIN.
owner_id INTEGER REFERENCES owners(id) says the column must match an id in owners. SQLite only checks this after , so put that line first.
With checks on, a bad link stops the statement with FOREIGN KEY constraint failed. NULL is still allowed, meaning no owner yet.
PRAGMA foreign_keys = ON;
CREATE TABLE owners (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE pets (
name TEXT,
owner_id INTEGER REFERENCES owners(id)
);
INSERT INTO owners (name) VALUES ('Ana'), ('Ben');
INSERT INTO pets VALUES ('Rex', 1), ('Luna', 2);
SELECT p.name, o.name AS owner FROM pets p JOIN owners o ON p.owner_id = o.id; With checks on, you also cannot delete an owner while pets still point at them.
guess first
The checks are not switched on. What happens?
Guess before you run it. Wrong guesses are how you learn, and nothing is marked.
CREATE TABLE owners (id INTEGER PRIMARY KEY, name TEXT);
CREATE TABLE pets (name TEXT, owner_id INTEGER REFERENCES owners(id));
INSERT INTO owners (name) VALUES ('Ana');
INSERT INTO pets VALUES ('Rex', 99);
SELECT * FROM pets;
your turn
Your turn. Link a pet to an owner.
Type a pet's name in the first blank. In the second, type an owner id: 1 for Ana or 2 for Ben. Afterwards, try 3 and read the error.
result
Your answer appears here as a table.
fix it
Biscuit belongs to Cleo, but will not go in. Fix it!
result
Your answer appears here as a table.
- Read the error, then work out which ids the two owners get.
- Ana gets id 1 and Cleo gets id 2. No owner has id 3.
- Change Biscuit's owner id from 3 to 2, then press run.
nailed it
your links can no longer break. :D
REFERENCES owners(id)makes a column a checked foreign key.- Switch checks on first with
PRAGMA foreign_keys = ON;. - A link to a missing row fails with
FOREIGN KEY constraint failed.
new words in your collection
- REFERENCES
- PRAGMA
This lesson isn’t saved. A free account remembers every lesson you finish.