Why keys matter
A table without keys is easy to fill and hard to trust. You can insert duplicate users, orphan orders, or reviews for products that do not exist.
Keys turn your feature idea from loose rows into rules the database can enforce. This is what makes your repo look serious.
Remember this
A primary key identifies one row in its own table. A foreign key stores the primary key of another table to show a real relationship.
Pick primary keys
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done
Feature example
Say you are building a campus event RSVP feature. One user can create many RSVPs. One event can have many RSVPs.
The rsvps table should not copy the full user and event details. It should store user_id and event_id, then foreign keys check that both rows exist.
-- schema.sql
CREATE TABLE users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE
);
CREATE TABLE events (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
venue TEXT NOT NULL,
starts_at TEXT NOT NULL
);
CREATE TABLE rsvps (
id INTEGER PRIMARY KEY,
user_id INTEGER NOT NULL,
event_id INTEGER NOT NULL,
status TEXT NOT NULL,
created_at TEXT NOT NULL,
FOREIGN KEY (user_id) REFERENCES users(id),
FOREIGN KEY (event_id) REFERENCES events(id)
);What this prevents
The database now blocks an RSVP for user_id 99 if there is no user with id 99. It also blocks an RSVP for event_id 50 if that event does not exist.
This helps during hackathons because bugs show up at insert time, not during your final demo.
Common mistake
Do not store related data as plain text when it should be a relationship. For example, rsvps.event_title looks easy, but it breaks when the event title changes.
Store event_id instead. Read the event title later with a JOIN in a later lesson.
Seed in order
Insert parent rows before child rows. For this example, insert users and events before rsvps.
If your seed file fails, check whether a foreign key points to a row you have not inserted yet.
-- seed.sql
INSERT INTO users (id, name, email) VALUES
(1, 'Asha Rao', '[email protected]'),
(2, 'Kabir Mehta', '[email protected]');
INSERT INTO events (id, title, venue, starts_at) VALUES
(1, 'AI Project Night', 'Lab 204', '2026-02-10 17:00');
INSERT INTO rsvps (id, user_id, event_id, status, created_at) VALUES
(1, 1, 1, 'going', '2026-02-01 12:30');Do this now
Do each one yourself, then tap it to tick it off. The ticks are only a checklist for you: they are not marked or scored.
0 of 5 done