Show contents
Chapter 4 of 7 · 20 min
Modelling: tables, keys and constraints
By the end of this chapter, you'll be able to
- Create a table with CREATE TABLE, a primary key and types
- Protect data with NOT NULL, UNIQUE, CHECK and foreign keys
- Split a flat table into linked tables (normalisation)
- Model a many-to-many relationship with a junction table
From spreadsheet to tables
The school's spreadsheet mixes three kinds of information: students, courses, and the fact that a student is enrolled in a course. Separating them is called normalising the database.
An enrolment now holds only two identifiers and a date: changing the email happens in one place.
Text description of the animation
- In the spreadsheet, Moussa's email is repeated on each of his enrolments.
- One missed update, and the database contradicts itself: that's an update anomaly.
- Each student is written only once, with an identifier.
- So is each course.
- An enrolment now holds only two identifiers and a date: changing the email happens in one place.
A student takes several courses, and a course has several students: it's a many-to-many relationship. It is always modelled with a junction table (enrolments), each row of which links one student and one course.
CREATE TABLE and constraints
PRAGMA foreign_keys = ON;
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
country TEXT NOT NULL REFERENCES countries(code)
);
CREATE TABLE courses (
id INTEGER PRIMARY KEY,
title TEXT NOT NULL,
seats INTEGER NOT NULL CHECK (seats > 0)
);
CREATE TABLE enrolments (
student_id INTEGER NOT NULL REFERENCES students(id),
course_id INTEGER NOT NULL REFERENCES courses(id),
date TEXT NOT NULL,
PRIMARY KEY (student_id, course_id)
);
INSERT INTO students VALUES (1, 'Moussa', 'moussa@example.org', 'SN'), (2, 'Linh', 'linh@example.org', 'VN'), (3, 'Rosa', 'rosa@example.org', 'PE');
INSERT INTO courses VALUES (1, 'Python for beginners', 20), (2, 'SQL', 15);
INSERT INTO enrolments VALUES (1, 1, '2026-09-01'), (1, 2, '2026-09-03'), (2, 2, '2026-09-04'), (3, 1, '2026-09-10');
SELECT co.title, COUNT(e.student_id) AS enrolled, GROUP_CONCAT(s.name, ', ') AS students
FROM courses AS co
LEFT JOIN enrolments AS e ON e.course_id = co.id
LEFT JOIN students AS s ON s.id = e.student_id
GROUP BY co.id
ORDER BY co.id;
title | enrolled | students
Python for beginners | 2 | Moussa, Rosa
SQL | 2 | Moussa, Linh
Each constraint is a rule that the database enforces, whatever program uses it:
| Constraint | Guarantees that… |
|---|---|
PRIMARY KEY | each row has a unique, non-null identifier |
NOT NULL | the column always has a value |
UNIQUE | no two rows ever have the same value (here, the email) |
CHECK (condition) | the condition is true for every row |
REFERENCES table(col) | the value exists in the other table (foreign key) |
PRIMARY KEY (student_id, course_id) is a composite key: a student can't enrol twice in the same course. GROUP_CONCAT(s.name, ', ') joins a group's names into a single text.
A violated constraint makes the statement fail, with a message saying which one:
PRAGMA foreign_keys = ON;
CREATE TABLE students (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
email TEXT NOT NULL UNIQUE,
country TEXT NOT NULL REFERENCES countries(code)
);
INSERT INTO students VALUES (1, 'Moussa', 'moussa@example.org', 'SN');
INSERT INTO students VALUES (2, 'Mo', 'moussa@example.org', 'SN');
UNIQUE constraint failed: students.email
That's good news: better an immediate error than a duplicate discovered six months later. The chosen types matter too: in SQLite, INTEGER, REAL and TEXT are the most common; dates are written as text in ISO format YYYY-MM-DD, which sorts correctly.
Your turn
Mini-lab: each country's citiesSQLite
Result
Click “Run”: the SQL engine (about 1 MB) will load in your browser the first time.
A fresh SQLite database is created on every run, in your browser · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor
Worked exercise
Solved exercise: the cities table
Create the mini-lab's cities table: an identifier, a mandatory name, a country code that must exist in countries, a population that is positive or zero, and a rule that forbids two cities with the same name in the same country. Insert four cities, then display for each country (including those without cities) the number of cities and the total population, sorted by decreasing population. The populations are orders of magnitude.
Hint 1
UNIQUE (name, country).Hint 2
countries with a LEFT JOIN. COALESCE(SUM(...), 0) replaces the NULL of an empty sum with 0.Show the solution and common mistakes
PRAGMA foreign_keys = ON;
CREATE TABLE cities (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
country TEXT NOT NULL REFERENCES countries(code),
population INTEGER CHECK (population >= 0),
UNIQUE (name, country)
);
INSERT INTO cities (name, country, population) VALUES
('Dakar', 'SN', 1400000), ('Saint-Louis', 'SN', 250000),
('Hanoi', 'VN', 8400000), ('Cusco', 'PE', 430000);
SELECT co.name AS country, COUNT(ci.id) AS cities, COALESCE(SUM(ci.population), 0) AS population
FROM countries AS co
LEFT JOIN cities AS ci ON ci.country = co.code
GROUP BY co.code
ORDER BY population DESC;
country | cities | population
Vietnam | 1 | 8400000
Senegal | 2 | 1650000
Peru | 1 | 430000
Canada | 0 | 0
INSERT INTO cities (name, country, population) lists the columns being filled: the id, missing, is assigned automatically by SQLite.
Common mistakes:
- Putting
UNIQUEonnamealone: two cities with the same name in different countries (there are several Saint-Louis in the world) become impossible. - Forgetting
PRAGMA foreign_keys = ON: the database accepts a city in a country that doesn't exist.
Summary
- 1Normalising means storing each piece of information once, in the table it belongs to.
- 2A many-to-many relationship is modelled with a junction table holding two foreign keys.
- 3PRIMARY KEY, NOT NULL, UNIQUE, CHECK and REFERENCES make the database itself enforce the rules.
- 4In SQLite, turn on PRAGMA foreign_keys = ON, otherwise foreign keys aren't checked.
Your progress is saved on this device. Create a free account to keep your progress on all your devices.