Schemas, Keys and Normalisation
💻 SQLDesign tables that stay correct: primary keys, foreign keys, constraints and sensible normal forms.
Bad schema design causes duplicate data, contradictory records and painful code. A little planning prevents years of cleanup.
- Choose primary and foreign keys.
- Apply NOT NULL, UNIQUE and CHECK.
- Recognise first, second and third normal form.
Constraints
Constraints let the database enforce rules so bad data never enters. Prefer them over application-only checks.
CREATE TABLE enrolments (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT NOT NULL,
course_id INT NOT NULL,
enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);Normalisation
First normal form: no repeating groups. Second: every non-key column depends on the whole key. Third: no column depends on another non-key column. In practice, store one fact in one place.
When to Denormalise
Reporting systems sometimes copy values to avoid expensive joins. Do this deliberately, after measuring, and keep a plan for keeping copies in sync.
Practice
- Add a CHECK constraint that keeps scores between 0 and 100.
- Explain why a student can enrol in a course only once.
- Split a table that stores a list of phone numbers in one column.
Hands-on exercise
Create an enrolments table with:
1. id primary key.
2. student_id and course_id, both NOT NULL.
3. Foreign keys to students and courses.
4. A UNIQUE constraint on the pair.
5. A grade column that only accepts A to F.
Recap
Keys connect tables, constraints protect correctness and normalisation keeps each fact in one place.
Example
CREATE TABLE enrolments (
id INT AUTO_INCREMENT PRIMARY KEY,
student_id INT NOT NULL,
course_id INT NOT NULL,
enrolled_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
UNIQUE (student_id, course_id),
FOREIGN KEY (student_id) REFERENCES students(id),
FOREIGN KEY (course_id) REFERENCES courses(id)
);
Exercises
1. id primary key.
2. student_id and course_id, both NOT NULL.
3. Foreign keys to students and courses.
4. A UNIQUE constraint on the pair.
5. A grade column that only accepts A to F.
Expected Output
A table that prevents duplicate enrolments and invalid grades.
Lesson Nav
SQL Course
0/9 lessons completed
- 1 What a Database Is Tutorial
- 2 Filtering and Sorting Tutorial
- 3 Aggregates and Grouping Tutorial
- 4 Joining Tables Tutorial
- 5 Subqueries and Common Table Expressions Tutorial
- 6 Inserting, Updating and Deleting Tutorial
- 7 Schemas, Keys and Normalisation Tutorial
- 8 Indexes and Query Performance Tutorial
- 9 Project: A Reporting Query Project