Bird
0
0

Which query correctly handles this?

hard📝 Application Q15 of 15
SQL - LEFT and RIGHT JOIN
You have tables students(id, name) and enrollments(student_id, course_id). Write a query to find students not enrolled in any course, considering some students may have NULL IDs. Which query correctly handles this?
ASELECT s.name FROM students s LEFT JOIN enrollments e ON s.id = e.student_id WHERE e.student_id IS NULL AND s.id IS NOT NULL;
BSELECT s.name FROM students s RIGHT JOIN enrollments e ON s.id = e.student_id WHERE s.id IS NULL;
CSELECT s.name FROM students s INNER JOIN enrollments e ON s.id = e.student_id WHERE s.id IS NULL;
DSELECT s.name FROM students s LEFT JOIN enrollments e ON s.id = e.student_id WHERE e.student_id IS NULL;
Step-by-Step Solution
Solution:
  1. Step 1: Use LEFT JOIN to find unmatched students

    LEFT JOIN students with enrollments keeps all students; unmatched enrollments are NULL.
  2. Step 2: Filter students without enrollments and exclude NULL student IDs

    WHERE e.student_id IS NULL finds students without courses; adding s.id IS NOT NULL excludes students with NULL IDs to avoid incorrect matches.
  3. Final Answer:

    SELECT s.name FROM students s LEFT JOIN enrollments e ON s.id = e.student_id WHERE e.student_id IS NULL AND s.id IS NOT NULL; -> Option A
  4. Quick Check:

    LEFT JOIN + right NULL + exclude NULL left keys = correct unmatched [OK]
Quick Trick: Exclude NULL keys on left table when filtering unmatched [OK]
Common Mistakes:
MISTAKES
  • Ignoring NULL IDs in left table
  • Using INNER JOIN which excludes unmatched rows
  • Using RIGHT JOIN incorrectly

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More SQL Quizzes