×

sql · level 2 · unit 6 · lesson 4

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. 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.