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;
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);
Look at which students are linked to the course titled 'Math 101' through the Enrollments table.
The query joins Students to Enrollments and then to Courses, filtering for 'Math 101'. Only Alice and Bob are enrolled in Math 101.
In a database, why do we use a junction table to represent many-to-many relationships?
Think about how many-to-many relationships connect two sets of data without repeating information.
A junction table links two tables in a many-to-many relationship and can hold extra info about the link, avoiding data duplication.
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;
Check if all selected columns are properly grouped or aggregated.
When using GROUP BY, all selected columns must be in GROUP BY or aggregated. 'c.title' is selected but not grouped or aggregated, causing a syntax error.
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;
Think about which column is used to join tables and filter data.
Adding an index on Enrollments.student_id speeds up the join operation by quickly locating matching 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;
Check the data in the junction table for repeated entries.
The Enrollments table has duplicate rows for student 2 and course 100, causing the query to return duplicates.