Video in progress
How are one-to-many and many-to-many relationships modeled in tables?
In one-to-many, the table on the "many" side gets an FK column holding the key of the "one" side. For many-to-many you create a separate junction table that stores the keys of both tables.
📖 Answer
One-to-many: one author has many books.
CREATE TABLE authors (id bigint PRIMARY KEY, name text NOT NULL);
CREATE TABLE books (
id bigint PRIMARY KEY,
title text NOT NULL,
author_id bigint NOT NULL REFERENCES authors(id)
);
CREATE INDEX idx_books_author ON books(author_id);
Many-to-many: a student enrolls in many courses, and a course has many students.
CREATE TABLE enrollments (
student_id bigint REFERENCES students(id),
course_id bigint REFERENCES courses(id),
enrolled_at timestamptz NOT NULL DEFAULT now(),
PRIMARY KEY (student_id, course_id)
);
CREATE INDEX idx_enrollments_course ON enrollments(course_id);
The PK (student_id, course_id) gives you two things: a student can't enroll in the same course twice, and lookups by student_id are fast. For the reverse direction (the students of a course) you need a separate index on course_id.
A practical tip: you almost always end up needing extra data on the junction table later, such as the enrollment date, a grade, a status. So in JPA, making the junction table its own entity instead of using @ManyToMany is often the better choice in the long run.
Sign up to mark studied questions and save your progress.