Lesson 25 of 30 · Designing Tables
Boss: Design Related SQL Tables with Keys and Constraints
The Architect blocks the way. Every test you pass deals damage — pass them all to defeat it and claim a loot chest.
The road to the Advanced Queries runs through a hall that hasn't been built yet, and the Architect, a towering golem of living stone, lets no one pass without a solid blueprint. The realm wants to hold its first tournaments. Design tables so sturdy that no bad record can ever get in, and the Architect will step aside.
Battle plan
This fight uses the whole chapter: CREATE TABLE, types, primary keys, constraints and foreign keys.
Tournaments and heroes have a many-to-many relationship: a tournament has many heroes, and a hero can enter many tournaments. A single foreign key can't express that, so you add a link table with one row per hero per tournament and a foreign key to each side. An entries row with tournament_id 1 and hero_id 8 means "hero 8 entered tournament 1". The course's completions table links heroes and quests in exactly this way.
Your building blocks:
| You want | Write |
|---|---|
| an auto-numbered id | id INTEGER PRIMARY KEY |
| a required value | NOT NULL |
| no duplicates | UNIQUE on a column, or UNIQUE (a, b) after the columns for a pair |
| a value when none is given | DEFAULT … |
| a rule on the value | CHECK (condition) |
| a link to another table | REFERENCES other_table(id), plus PRAGMA foreign_keys = ON; |
Assignment
-
Switch on foreign key enforcement.
-
Create the table
tournaments:Column Type Rules idINTEGERprimary key nameTEXTrequired; no two tournaments may share a name cityTEXTrequired entry_feeINTEGERrequired; 0when not given; never negative -
Create the link table
entries:Column Type Rules idINTEGERprimary key tournament_idINTEGERrequired; references tournaments(id)hero_idINTEGERrequired; references heroes(id)A hero may enter each tournament only once but can enter several different tournaments, so the same
(tournament_id, hero_id)pair must never appear twice. -
Fill both tables without giving ids:
'Spring Joust'in'Eldermoor'with an entry fee of50, then'Mage Duel Cup'in'Mistvale'with no fee given. They become tournaments 1 and 2.- Hugo Stonebeard (hero
8) and Borin Ironfist (hero2) enter the Spring Joust; Cyra Moonweaver (hero3) and Gwen Stormcaller (hero7) enter the Mage Duel Cup.
The Architect tests every wall of your design with ten blows. Make all ten tests pass.
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 .