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
Many-to-many with junction tables
📖 Scenario: You are building a simple database for a library. Books can have multiple authors, and authors can write multiple books. To represent this many-to-many relationship, you will use a junction table.
🎯 Goal: Create tables for Books and Authors, then create a junction table called BookAuthors to link books and authors. Insert sample data and write a query to find all authors for a specific book.
📋 What You'll Learn
Create a Books table with columns BookID (primary key) and Title.
Create an Authors table with columns AuthorID (primary key) and Name.
Create a junction table BookAuthors with columns BookID and AuthorID to link books and authors.
Insert at least two books and three authors with appropriate links in BookAuthors.
Write a query to select all author names for the book titled 'The Great Adventure'.
💡 Why This Matters
🌍 Real World
Many real-world databases use many-to-many relationships, such as students enrolled in multiple courses or products with multiple tags.
💼 Career
Understanding how to model and query many-to-many relationships is essential for database design and is a common task in software development and data analysis jobs.
Progress0 / 4 steps
1
Create Books and Authors tables
Write SQL statements to create a table called Books with columns BookID as an integer primary key and Title as text. Also create a table called Authors with columns AuthorID as an integer primary key and Name as text.
SQL
Hint
Use CREATE TABLE statements with the specified columns and types.
2
Create the junction table BookAuthors
Write a SQL statement to create a junction table called BookAuthors with columns BookID and AuthorID. Both columns should be integers and together form the primary key. This table links books and authors.
SQL
Hint
Define both columns as integers and set a composite primary key on both.
3
Insert sample data into Books, Authors, and BookAuthors
Insert two books into Books: (1, 'The Great Adventure') and (2, 'Mystery of the Night'). Insert three authors into Authors: (1, 'Alice Smith'), (2, 'Bob Johnson'), and (3, 'Carol Lee'). Then insert links into BookAuthors: book 1 with authors 1 and 2, and book 2 with author 3.
SQL
Hint
Use INSERT INTO statements with the exact values given.
4
Query authors for 'The Great Adventure'
Write a SQL query to select the Name of all authors who wrote the book titled 'The Great Adventure'. Use the tables Books, Authors, and BookAuthors with appropriate joins.
SQL
Hint
Use JOINs to connect the three tables and filter by the book title.
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
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.
Step 2: Role of junction table
A junction table holds pairs of foreign keys from both tables to link related records without duplicating data.
Final Answer:
To store pairs of related records from two tables using foreign keys -> Option A
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?
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
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.
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.
Final Answer:
A list of authors and the titles of books they wrote -> Option A
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
Step 1: Analyze the JOIN conditions
The JOINs already match Student.ID to StudentCourse.StudentID and Course.ID to StudentCourse.CourseID.
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.
Final Answer:
The WHERE clause is unnecessary because JOIN already matches IDs -> Option C
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
Step 1: Count total projects
Find total number of projects from Project table.
Step 2: Group EmployeeProject by EmployeeID
Count how many projects each employee works on.
Step 3: Use HAVING to compare counts
Only select employees whose project count equals total projects count.
Final Answer:
Use GROUP BY EmployeeID and HAVING count of projects equal to total projects count -> Option B
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