TopicsCheat sheetLessons
Lurndo › Topics › Keys

Learn SQL: Keys

Keys connect tables

Yasmine opens the database. "Why does every player have a number instead of the name of their team? Nobody can read that." That number is exactly the clever part.

The primary key

Every table has an id column with a unique number per row: the primary key. Two teams can share a coach or play in the same category, but never have the same id.

That way you can point at any row without a doubt.

SELECT * FROM teams
Result
idnamecategorycoach_id
1U11youth3
2U13youth1
3U15youthNULL
4Women Aseniors2
5Men Aseniors4
6VeteransseniorsNULL

The foreign key

In players you'll find team_id: the id of the team someone plays in. A column that points at the primary key of another table is called a foreign key.

Thanks to it, each team name is stored only once in the database. Rename a team and you change one row, not twenty.

SELECT name, team_id FROM players
Result
nameteam_id
Jonas Verhoeven5
Wout Hermans5
Bram De Smet5
Yannick Diallo5
Elke Van Dyck4
Nora Aerts4
Charlotte Maes4
Ines Goossens4
SELECT id, name FROM teams
teams
idname
1U11
2U13
3U15
4Women A
5Men A
6Veterans

Try it yourself

Show the name and position of the U15 players. Look up the id first.

Ready for more?

The full lesson has 6 exercises, from easy to challenging, with hints, points and a streak you can build.

Start the lesson
← PreviousFiltering groups with HAVINGNext →Linking tables with JOIN
SQL topicsCheat sheetExcelLeaderboardAccountPrivacyNederlands