Advertisement
Intermediate Node.js, Databases

What is the difference between a one-to-many and a many-to-many relationship in a relational database, and how is each modeled?

Short answer

A one-to-many relationship (like one author having many books) is modeled with a foreign key on the 'many' side's table pointing back to the 'one' side.

Save Node.js mock interview
Advertisement
AModel answer
A one-to-many relationship (like one author having many books) is modeled with a foreign key on the 'many' side's table pointing back to the 'one' side. A many-to-many relationship (like many students enrolled in many courses) requires an intermediate junction table containing foreign keys to both related tables, since neither table alone can hold a foreign key representing multiple associations on both sides.
-- One-to-many: books.author_id references authors.id
CREATE TABLE books (id SERIAL PRIMARY KEY, author_id INT REFERENCES authors(id));

-- Many-to-many: a junction table
CREATE TABLE enrollments (
  student_id INT REFERENCES students(id),
  course_id INT REFERENCES courses(id),
  PRIMARY KEY (student_id, course_id)
);
Real-world example
A course-registration system models the many-to-many relationship between students and courses using an 'enrollments' junction table, which also conveniently stores relationship-specific data like the enrollment date and grade that wouldn't fit naturally on either the students or courses table alone.
Likely follow-ups
  • What additional data can a junction table hold beyond just the two foreign keys, and why is that useful?
  • How does an ORM like Sequelize or a Mongoose implementation model a many-to-many relationship in code?
Related topics