A database has a 'Students' table with columns: StudentID (primary key), Name, Major. Another table 'Enrollments' has columns: EnrollmentID (primary key), StudentID (foreign key), CourseID. Which SQL query correctly lists each student's name and their enrolled courses by joining the tables?
Trap 1: SELECT Name, CourseID FROM Students RIGHT JOIN Enrollments ON…
RIGHT JOIN returns all rows from the right table (Enrollments) and matching rows from Students. Students without enrollments are excluded, but enrollments without a matching student (if any) would appear with NULL for Name. This does not match the requirement to list each student's enrolled courses.
Trap 2: SELECT Name, CourseID FROM Students, Enrollments WHERE…
The implicit comma join without a WHERE clause produces a Cartesian product (each row of Students paired with each row of Enrollments). Although the WHERE clause here is present, the syntax is outdated and less clear; it functions as an INNER JOIN, but the query is correct. However, it is not the best practice; optionally, it is acceptable but not the only correct syntax.
Trap 3: SELECT Name, CourseID FROM Students LEFT JOIN Enrollments ON…
LEFT JOIN returns all students, even those without enrollments, who would show NULL for CourseID. This does not meet the requirement to list only students with enrolled courses.
- A
SELECT Name, CourseID FROM Students RIGHT JOIN Enrollments ON Students.StudentID = Enrollments.StudentID;
Why it fails: RIGHT JOIN returns all rows from the right table (Enrollments) and matching rows from Students. Students without enrollments are excluded, but enrollments without a matching student (if any) would appear with NULL for Name. This does not match the requirement to list each student's enrolled courses.
- B
SELECT Name, CourseID FROM Students INNER JOIN Enrollments ON Students.StudentID = Enrollments.StudentID;
An INNER JOIN on Students.StudentID = Enrollments.StudentID matches each student row to their enrolment rows via the foreign key, returning Name alongside CourseID. Rows without matching enrolments are excluded, correctly pairing students with their enrolled courses.
- C
SELECT Name, CourseID FROM Students, Enrollments WHERE Students.StudentID = Enrollments.StudentID;
Why it fails: The implicit comma join without a WHERE clause produces a Cartesian product (each row of Students paired with each row of Enrollments). Although the WHERE clause here is present, the syntax is outdated and less clear; it functions as an INNER JOIN, but the query is correct. However, it is not the best practice; optionally, it is acceptable but not the only correct syntax.
- D
SELECT Name, CourseID FROM Students LEFT JOIN Enrollments ON Students.StudentID = Enrollments.StudentID;
Why it fails: LEFT JOIN returns all students, even those without enrollments, who would show NULL for CourseID. This does not meet the requirement to list only students with enrolled courses.