Full answer
sql
PRAGMA foreign_keys = ON;
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrolments (
student_id INTEGER NOT NULL REFERENCES students(id),
course_id INTEGER NOT NULL REFERENCES courses(id),
marks INTEGER CHECK (marks BETWEEN 0 AND 100),
PRIMARY KEY (student_id, course_id)
);
CREATE INDEX enrolments_course ON enrolments(course_id);
INSERT INTO students VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO courses VALUES (10, 'Databases'), (20, 'Algorithms');
INSERT INTO enrolments VALUES (1, 10, 88), (1, 20, 92), (2, 10, 75);
SELECT c.title, COUNT(*) AS students FROM enrolments e JOIN courses c ON c.id = e.course_id GROUP BY c.id, c.title ORDER BY c.title;| title | students |
|---|---|
| Algorithms | 1 |
| Databases | 2 |
Each enrolment is one row, so a student can take many courses and a course can have many students. The composite primary key stops a student enrolling twice in the same course. An extra index on course_id serves "who is in this course?", because the primary key index starts with student_id.
marks describes the pair, so it lives here. Putting it on students would only allow one mark per student, and on courses one mark per course.
If students may retake a course, the key must change, for example to (student_id, course_id, term). That requirement is worth asking about in an interview.
sql
PRAGMA foreign_keys = ON;
CREATE TABLE students (id INTEGER PRIMARY KEY, name TEXT NOT NULL);
CREATE TABLE courses (id INTEGER PRIMARY KEY, title TEXT NOT NULL);
CREATE TABLE enrolments (
student_id INTEGER NOT NULL REFERENCES students(id),
course_id INTEGER NOT NULL REFERENCES courses(id),
marks INTEGER CHECK (marks BETWEEN 0 AND 100),
PRIMARY KEY (student_id, course_id)
);
CREATE INDEX enrolments_course ON enrolments(course_id);
INSERT INTO students VALUES (1, 'Asha'), (2, 'Ben');
INSERT INTO courses VALUES (10, 'Databases'), (20, 'Algorithms');
INSERT INTO enrolments VALUES (1, 10, 88), (1, 20, 92), (2, 10, 75);
SELECT c.title, COUNT(*) AS students FROM enrolments e JOIN courses c ON c.id = e.course_id GROUP BY c.id, c.title ORDER BY c.title;Checked on SQLite 3.46.1, run twice with identical output.
Key points
- Many-to-many needs a junction table
- Foreign keys point to both parents
- Composite primary key prevents duplicate pairs
- Relationship attributes belong on the junction table
Common mistakes
- Storing a list of course ids on the student row
- Forgetting the index for lookups by the second column
Follow-ups
- How would you support retakes?
- How would you list courses with no students?
Tips
- Ask about retakes before fixing the key