Many-to-many with junction tables in SQL - Time & Space Complexity
When working with many-to-many relationships in databases, we often use junction tables to connect data.
We want to understand how the time to get results grows as the data grows.
Analyze the time complexity of the following SQL query.
SELECT students.name, courses.title
FROM students
JOIN student_courses ON students.id = student_courses.student_id
JOIN courses ON courses.id = student_courses.course_id
WHERE students.id = 123;
This query finds all courses taken by a specific student using a junction table.
Look for repeated steps that affect performance.
- Primary operation: Scanning the junction table rows matching the student ID.
- How many times: Once for each course the student takes.
As the number of courses a student takes grows, the query does more work.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 10 lookups in the junction table and courses table |
| 100 | About 100 lookups |
| 1000 | About 1000 lookups |
Pattern observation: The work grows roughly in direct proportion to the number of courses linked to the student.
Time Complexity: O(n)
This means the time to get all courses grows linearly with how many courses the student has.
[X] Wrong: "The query time depends on the total number of students or courses in the database."
[OK] Correct: The query only processes rows related to one student, so the total database size does not directly affect this query's time.
Understanding how many-to-many queries scale helps you explain database performance clearly and confidently.
What if we changed the query to find all students enrolled in a specific course? How would the time complexity change?