Designing a Good Schema
Learning objective
By the end of this lesson you will be able to design tables with relationships that avoid duplication.
A good database design stores each fact once and links related facts together. This lesson covers the key ideas.
The problem with duplication
Storing the same information in many places causes inconsistency — update one copy and the others go stale. Good design stores each fact once.
Relationships
- One-to-one — one row relates to at most one other row
- One-to-many — one row relates to many rows (a subject has many topics)
- Many-to-many — many rows relate to many rows (students ↔ courses)
Example: students, enrollments, courses
A student takes many courses and a course has many students — a many-to-many relationship. SQL handles it with a join table called enrollments.
CREATE TABLE enrollments (
student_id INT,
course_id INT,
PRIMARY KEY (student_id, course_id)
);Foreign keys
A foreign key is a column that points at a primary key in another table. It is what turns separate tables into a related database.
Practice exercise
Sketch tables for a library: books, members and loans. Where do you put the foreign keys?
Check your understanding
1. What does a foreign key do?
2. Students and courses form which relationship?
Self-graded — answer then check below.