Lesson 24 of 30 · Designing Tables
SQL Foreign Keys: REFERENCES, ALTER TABLE and DROP TABLE
Tables rarely stand alone. Every purchase belongs to a hero and an item, and most heroes belong to a guild. A foreign key is the column that makes such a link, and once the database knows about it, it can refuse rows that point nowhere.
REFERENCES: declaring the link
purchases.hero_id stores the id of a hero. In the course database it's declared like this:
CREATE TABLE purchases (
id INTEGER PRIMARY KEY,
hero_id INTEGER NOT NULL REFERENCES heroes(id),
item_id INTEGER NOT NULL REFERENCES items(id),
quantity INTEGER NOT NULL DEFAULT 1,
bought_on TEXT NOT NULL
);
REFERENCES heroes(id) means: every value in this column must be the id of an existing hero. heroes is the parent table and purchases the child. The long form, FOREIGN KEY (hero_id) REFERENCES heroes(id) written after the last column, means the same thing.
Switching enforcement on
For historical reasons, SQLite does not enforce foreign keys until you switch them on. The setting lasts for the connection, so put it at the top of your code:
PRAGMA foreign_keys = ON;
INSERT INTO purchases (hero_id, item_id, bought_on)
VALUES (99, 1, '2025-08-01');
-- Error: FOREIGN KEY constraint failed (there is no hero 99)
PostgreSQL, MySQL and SQL Server always enforce foreign keys. The same error stops you from deleting a parent that still has children: DELETE FROM heroes WHERE id = 1; fails while Aria's purchases point at her, so you delete the children first. If you'd rather have the children removed automatically, declare the link as REFERENCES heroes(id) ON DELETE CASCADE.
Without the pragma, both statements succeed silently and leave orphan rows behind.
Changing a table: ALTER TABLE
Tables evolve. ALTER TABLE … ADD COLUMN adds a column to an existing table and keeps all its rows:
ALTER TABLE heroes ADD COLUMN title TEXT;
ALTER TABLE items ADD COLUMN stock INTEGER NOT NULL DEFAULT 0;
Existing rows get the column's default, or NULL when there is none. That's why a new NOT NULL column needs a DEFAULT: the rows already in the table must get some value. ALTER TABLE can also rename a table (RENAME TO) or a column (RENAME COLUMN … TO …).
Removing a table: DROP TABLE
DROP TABLE IF EXISTS taverns;
DROP TABLE deletes the table and every row in it. Compare DELETE FROM taverns;, which empties the table but keeps it. IF EXISTS avoids an error when there's no such table.
Common mistakes
- Forgetting
PRAGMA foreign_keys = ON. In SQLite,REFERENCESon its own is only documentation. - Referencing the wrong column. A foreign key points at the parent's primary key,
heroes(id), not at a name. - Adding a
NOT NULLcolumn without aDEFAULT. It fails withCannot add a NOT NULL column with default value NULL. DROP TABLEwhen you meantDELETE. There's no undo.
Assignment
Heroes are getting animal companions. In this order:
-
Switch on foreign key enforcement.
-
Create the table
companions:Column Type Rules idINTEGERprimary key nameTEXTrequired speciesTEXTrequired hero_idINTEGERrequired; references heroes(id) -
Add two companions:
'Ember', a'fox', for Aria Swiftwind (hero1), and'Grumble', a'badger', for Hugo Stonebeard (hero8). -
Guilds want mottos: add a
mottocolumn of typeTEXTtoguilds, then set the motto of the Iron Wall (guild2) to'Hold the line'. -
This lesson's database has an old table,
old_bounties, that nobody uses any more. Drop it.
Curious? Add a companion for hero 99 at the end and press Run to see the foreign key error. Remove it again before you submit.
Premium lesson
Unlock the full Learn SQL course
- All 30 lessons, bosses and quizzes — lifetime access
- One payment of $35, no subscription
- Finish within 30 days and claim $10.50 (30%) back
Want more than one course?
The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.
Keep learning
Need a quick reminder? The SQL cheat sheet has every topic of Learn SQL on one page.
Lesson last updated on .