w3resource

Build a Junction Table for Many-to-Many Relationships


Designing a Junction Table for Many-to-Many Relationships

Write a SQL query to design a junction table for a many-to-many relationship.

Solution:

-- Tables representing entities in a many-to-many relationship.
CREATE TABLE Students (
    StudentID INT PRIMARY KEY,
    Name VARCHAR(100)
);

CREATE TABLE Courses (
    CourseID INT PRIMARY KEY,
    CourseName VARCHAR(100)
);

-- Junction table to resolve many-to-many relationship.
CREATE TABLE StudentCourses (
    StudentID INT,
    CourseID INT,
    PRIMARY KEY (StudentID, CourseID),
    FOREIGN KEY (StudentID) REFERENCES Students(StudentID),
    FOREIGN KEY (CourseID) REFERENCES Courses(CourseID)
);

Explanation:

  • Purpose of the Query :
    • The goal is to design a junction table to represent a many-to-many relationship between students and courses.
  • Key Components :
    • StudentCourses: Links students to courses using foreign keys.
    • Composite primary key ensures unique combinations of student and course IDs.
  • Why use Junction Tables? :
    • Junction tables resolve many-to-many relationships by introducing an intermediary table.
    • They simplify querying and maintaining relationships.
  • Real-World Application :
    • In enrollment systems, junction tables track which students are enrolled in which courses.

Notes:

  • Junction tables often include additional attributes (e.g., enrollment date).
  • Ensure proper indexing for efficient joins.
  • Avoid redundant entries in the junction table.

For more Practice: Solve these Related Problems:

  • Write a SQL query to design a junction table for a many-to-many relationship between books and authors.
  • Write a SQL query to create a junction table for a many-to-many relationship between students and extracurricular activities.
  • Write a SQL query to design a junction table for a many-to-many relationship between employees and projects.
  • Write a SQL query to create a junction table for a many-to-many relationship between products and suppliers.


Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous SQL Exercise: Identifying and Resolving Update Anomalies.
Next SQL Exercise: Denormalizing for Performance Optimization.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.