New! Explore our Programming Academy and AI Tutor - learn to code from scratch, free to start. Explore Now
Programming› SQL› Schemas, Keys and Normalisation

Schemas, Keys and Normalisation

💻 SQL

Design tables that stay correct: primary keys, foreign keys, constraints and sensible normal forms.

Lesson 7 of 9 Tutorial
0 of 9 completed

Bad schema design causes duplicate data, contradictory records and painful code. A little planning prevents years of cleanup.

By the end of this lesson you can:
  • 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.

Tip Name foreign keys consistently: student_id in enrolments points to students.id. Consistent names make joins obvious.

Practice

  1. Add a CHECK constraint that keeps scores between 0 and 100.
  2. Explain why a student can enrol in a course only once.
  3. 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

Exercise 1. Enrolment table Hard
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.
SQL exercise-1.sql
Expected Output
A table that prevents duplicate enrolments and invalid grades.

Lesson Nav

Lesson sections