Skip to main content
Albero Academy

Keys, Relationships & Joins

Model related data with primary and foreign keys, enforce integrity, and combine tables with the join types.

Chapter 3MySQL16 min readBeginner friendly
  • #MySQL
  • #Joins
  • #Keys

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:

a foreign key
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:

JoinReturns
INNER JOINOnly rows with a match in both tables
LEFT JOINAll left rows + matches (NULLs where none)
RIGHT JOINAll right rows + matches
CROSS JOINEvery combination (rarely wanted)
joining tables
SELECT s.name, p.name AS programme
FROM students s
JOIN programmes p ON s.programme_id = p.id;
-- LEFT JOIN keeps students even if programme_id is NULL
SELECT s.name, p.name AS programme
FROM students s
LEFT 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

  1. 01Store each fact once and link tables — never copy the same value across many rows.
  2. 02A primary key identifies a row; a foreign key references another table's primary key.
  3. 03Foreign keys enforce referential integrity — you can't reference a row that doesn't exist.
  4. 04INNER JOIN keeps only matches; LEFT JOIN keeps all left rows with NULLs where none match.
  5. 05Use table aliases and qualify columns (s.name) to keep joins clear.