Bird
Raised Fist0
SQLquery~20 mins

Many-to-many with junction tables in SQL - Practice Problems & Coding Challenges

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Challenge - 5 Problems
🎖️
Many-to-many Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
query_result
intermediate
2:00remaining
Find all students enrolled in 'Math 101'

Given these tables:

Students(id, name)
Courses(id, title)
Enrollments(student_id, course_id)

What is the output of this query?

SELECT s.name FROM Students s
JOIN Enrollments e ON s.id = e.student_id
JOIN Courses c ON e.course_id = c.id
WHERE c.title = 'Math 101'
ORDER BY s.name;
SQL
CREATE TABLE Students (id INT, name VARCHAR(50));
CREATE TABLE Courses (id INT, title VARCHAR(50));
CREATE TABLE Enrollments (student_id INT, course_id INT);

INSERT INTO Students VALUES (1, 'Alice'), (2, 'Bob'), (3, 'Charlie');
INSERT INTO Courses VALUES (10, 'Math 101'), (20, 'History 201');
INSERT INTO Enrollments VALUES (1, 10), (2, 10), (3, 20);
A
Alice
Bob
B
Alice
Charlie
C
Bob
Charlie
D
Alice
Bob
Charlie
Attempts:
2 left
💡 Hint

Look at which students are linked to the course titled 'Math 101' through the Enrollments table.

🧠 Conceptual
intermediate
1:30remaining
Why use a junction table in many-to-many relationships?

In a database, why do we use a junction table to represent many-to-many relationships?

ATo enforce one-to-one relationships between tables
BTo avoid using primary keys in the related tables
CTo combine two tables into one for faster queries
DTo store additional data about the relationship and link two tables without duplicating data
Attempts:
2 left
💡 Hint

Think about how many-to-many relationships connect two sets of data without repeating information.

📝 Syntax
advanced
1:30remaining
Identify the syntax error in this many-to-many query

What error does this SQL query raise?

SELECT s.name, c.title
FROM Students s
JOIN Enrollments e ON s.id = e.student_id
JOIN Courses c ON e.course_id = c.id
WHERE c.title = 'History 201'
GROUP BY s.name;
ASyntax error: missing semicolon at end
BNo error, query runs correctly
CSyntax error: 'c.title' must be in GROUP BY or aggregated
DRuntime error: table 'Enrollments' does not exist
Attempts:
2 left
💡 Hint

Check if all selected columns are properly grouped or aggregated.

optimization
advanced
1:30remaining
Optimize this many-to-many query for performance

Which change will improve performance of this query?

SELECT s.name, COUNT(*) AS course_count
FROM Students s
JOIN Enrollments e ON s.id = e.student_id
GROUP BY s.name
ORDER BY course_count DESC;
AAdd an index on Enrollments.student_id
BAdd an index on Students.name
CRemove GROUP BY clause
DAdd an index on Enrollments.course_id
Attempts:
2 left
💡 Hint

Think about which column is used to join tables and filter data.

🔧 Debug
expert
2:30remaining
Why does this many-to-many query return duplicate rows?

Given these tables and data:

Students(id, name): (1, 'Anna'), (2, 'Ben')
Courses(id, title): (100, 'Physics'), (200, 'Chemistry')
Enrollments(student_id, course_id): (1, 100), (1, 200), (2, 100), (2, 100)

What causes this query to return duplicate rows?

SELECT s.name, c.title
FROM Students s
JOIN Enrollments e ON s.id = e.student_id
JOIN Courses c ON e.course_id = c.id
ORDER BY s.name, c.title;
AJOIN condition is incorrect and duplicates rows
BDuplicate rows in Enrollments cause repeated results
CMissing DISTINCT keyword in SELECT
DCourses table has duplicate titles causing duplicates
Attempts:
2 left
💡 Hint

Check the data in the junction table for repeated entries.

Practice

(1/5)
1. What is the main purpose of a junction table in a many-to-many relationship?
easy
A. To store pairs of related records from two tables using foreign keys
B. To store all data from both tables in one place
C. To replace one of the original tables completely
D. To create a one-to-one relationship between tables

Solution

  1. Step 1: Understand many-to-many relationships

    Many-to-many means each record in one table can relate to many records in another table, and vice versa.
  2. Step 2: Role of junction table

    A junction table holds pairs of foreign keys from both tables to link related records without duplicating data.
  3. Final Answer:

    To store pairs of related records from two tables using foreign keys -> Option A
  4. Quick Check:

    Junction table = pairs of foreign keys [OK]
Hint: Junction tables link two tables with pairs of keys [OK]
Common Mistakes:
  • Thinking junction table stores all data from both tables
  • Confusing junction table with a single main table
  • Assuming junction table creates one-to-one links
2. Which SQL statement correctly creates a junction table named StudentCourse linking Student and Course tables by their IDs?
easy
A. CREATE TABLE StudentCourse (StudentID INT, CourseID INT, FOREIGN KEY (StudentID) REFERENCES Student(ID));
B. CREATE TABLE StudentCourse (ID INT PRIMARY KEY, StudentID INT, CourseID INT);
C. CREATE TABLE StudentCourse (StudentID INT UNIQUE, CourseID INT UNIQUE);
D. CREATE TABLE StudentCourse (StudentID INT, CourseID INT, PRIMARY KEY (StudentID, CourseID));

Solution

  1. Step 1: Define junction table columns

    It needs two columns for foreign keys: StudentID and CourseID.
  2. Step 2: Set primary key on both columns

    Primary key on (StudentID, CourseID) ensures unique pairs and no duplicates.
  3. Final Answer:

    CREATE TABLE StudentCourse (StudentID INT, CourseID INT, PRIMARY KEY (StudentID, CourseID)); -> Option D
  4. Quick Check:

    Junction table needs composite primary key [OK]
Hint: Use composite primary key on both foreign keys [OK]
Common Mistakes:
  • Using UNIQUE on individual columns instead of composite key
  • Missing one foreign key column
  • Not defining primary key on the pair
3. Given tables Author, Book, and junction table AuthorBook with columns AuthorID and BookID, what does this query return?
SELECT Author.Name, Book.Title FROM Author
JOIN AuthorBook ON Author.ID = AuthorBook.AuthorID
JOIN Book ON Book.ID = AuthorBook.BookID;
medium
A. A list of authors and the titles of books they wrote
B. A list of books without any author names
C. A list of all authors with all books, including unrelated pairs
D. An error because of missing WHERE clause

Solution

  1. Step 1: Understand JOINs with junction table

    The query joins Author to AuthorBook by AuthorID, then AuthorBook to Book by BookID, linking authors to their books.
  2. Step 2: Result of the query

    It returns pairs of author names and book titles where the author wrote the book, no unrelated pairs included.
  3. Final Answer:

    A list of authors and the titles of books they wrote -> Option A
  4. Quick Check:

    JOINs with junction table = related pairs only [OK]
Hint: JOIN junction table to get related pairs only [OK]
Common Mistakes:
  • Thinking it returns all combinations of authors and books
  • Expecting an error without WHERE clause
  • Ignoring the role of junction table in filtering
4. You wrote this query to find all students and their courses:
SELECT Student.Name, Course.Title FROM Student
JOIN StudentCourse ON Student.ID = StudentCourse.StudentID
JOIN Course ON Course.ID = StudentCourse.CourseID
WHERE StudentCourse.StudentID = Student.ID;

But it has a problem. What is the problem?
medium
A. The WHERE clause is redundant and causes a syntax error
B. Missing alias for tables causes ambiguity
C. The WHERE clause is unnecessary because JOIN already matches IDs
D. StudentCourse.CourseID is missing in the WHERE clause

Solution

  1. Step 1: Analyze the JOIN conditions

    The JOINs already match Student.ID to StudentCourse.StudentID and Course.ID to StudentCourse.CourseID.
  2. Step 2: Check the WHERE clause

    The WHERE clause repeats the JOIN condition, which is unnecessary but not an error; however, it does not filter or add value.
  3. Final Answer:

    The WHERE clause is unnecessary because JOIN already matches IDs -> Option C
  4. Quick Check:

    JOIN matches IDs, WHERE clause redundant [OK]
Hint: JOIN conditions handle matching; WHERE often not needed here [OK]
Common Mistakes:
  • Assuming WHERE clause causes syntax error
  • Adding unnecessary conditions that duplicate JOINs
  • Confusing alias usage with errors
5. You have tables Employee, Project, and junction table EmployeeProject with EmployeeID and ProjectID. How do you find employees who work on all projects listed in Project?
hard
A. Join EmployeeProject and Project, then filter with WHERE ProjectID IS NOT NULL
B. Use GROUP BY EmployeeID and HAVING count of projects equal to total projects count
C. Select employees with a simple JOIN to EmployeeProject without grouping
D. Use DISTINCT on EmployeeID in EmployeeProject without counting projects

Solution

  1. Step 1: Count total projects

    Find total number of projects from Project table.
  2. Step 2: Group EmployeeProject by EmployeeID

    Count how many projects each employee works on.
  3. Step 3: Use HAVING to compare counts

    Only select employees whose project count equals total projects count.
  4. Final Answer:

    Use GROUP BY EmployeeID and HAVING count of projects equal to total projects count -> Option B
  5. Quick Check:

    Group and count projects per employee = all projects [OK]
Hint: Group by employee, HAVING count = total projects [OK]
Common Mistakes:
  • Not grouping and counting projects per employee
  • Using WHERE instead of HAVING for aggregate filtering
  • Ignoring total projects count in comparison