Sobes.tech
Junior — Middle

How is a Many-to-Many relationship usually implemented in a relational database?

sobes.tech AI

Answer from AI

In relational databases, a Many-to-Many relationship is implemented through an intermediate (junction) table that contains foreign keys to both related tables.

For example, there are tables Students and Courses. One student can attend many courses, and one course can have many students. To establish this relationship, a StudentCourses table is created with two columns:

  • student_id — foreign key to Students
  • course_id — foreign key to Courses

This allows efficient storage and querying of Many-to-Many relationships.

Example schema:

CREATE TABLE Students (
  id INT PRIMARY KEY,
  name VARCHAR(100)
);

CREATE TABLE Courses (
  id INT PRIMARY KEY,
  title VARCHAR(100)
);

CREATE TABLE StudentCourses (
  student_id INT,
  course_id INT,
  PRIMARY KEY (student_id, course_id),
  FOREIGN KEY (student_id) REFERENCES Students(id),
  FOREIGN KEY (course_id) REFERENCES Courses(id)
);