Real data is relational: students belong to programmes, orders belong to customers. Instead of repeating a programme's details on every student row, you store programmes once and link to them. This chapter is how those links work and how you query across them.
Why split data across tables?
Storing a programme's name and fee on every student row means updating hundreds of rows to fix one typo — and rows can disagree with each other. Keep each fact in exactly one place and reference it. That's the whole point of a relational database.
Primary & foreign keys
A primary key uniquely identifies a row in its own table. A foreign key is a column that points at another table's primary key, and the database enforces that the reference is valid:
CREATE TABLE programmes (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100) NOT NULL);CREATE TABLE students (id INT AUTO_INCREMENT PRIMARY KEY,name VARCHAR(100),programme_id INT,FOREIGN KEY (programme_id) REFERENCES programmes(id));
Joins
A join stitches related rows from two tables into one result set. The four you'll use:
| Join | Returns |
|---|---|
INNER JOIN | Only rows with a match in both tables |
LEFT JOIN | All left rows + matches (NULLs where none) |
RIGHT JOIN | All right rows + matches |
CROSS JOIN | Every combination (rarely wanted) |
SELECT s.name, p.name AS programmeFROM students sJOIN programmes p ON s.programme_id = p.id;-- LEFT JOIN keeps students even if programme_id is NULLSELECT s.name, p.name AS programmeFROM students sLEFT JOIN programmes p ON s.programme_id = p.id;
Table aliases (students s) keep joins readable, and qualifying columns (s.name) removes ambiguity when both tables have a column of the same name.
A word on normalisation
Normalisation is the practice of organising tables so each fact lives in one place, linked by keys. It removes duplication and update anomalies. In practice: if you find yourself copying the same value into many rows, it probably wants its own table.
Practice
Add a programmes table and a programme_id foreign key to students. Insert a few programmes and students, then write an INNER JOIN listing each student with their programme name, and a LEFT JOIN that also shows students with no programme yet.
Key takeaways
- 01Store each fact once and link tables — never copy the same value across many rows.
- 02A primary key identifies a row; a foreign key references another table's primary key.
- 03Foreign keys enforce referential integrity — you can't reference a row that doesn't exist.
- 04INNER JOIN keeps only matches; LEFT JOIN keeps all left rows with NULLs where none match.
- 05Use table aliases and qualify columns (s.name) to keep joins clear.
