SQL Practice Problem #019

Find students enrolled in at least one course

Return student names for students who appear in the enrollments table.

Problem

Task

Return student names for students who appear in the enrollments table.

Schema

Table Schema

students(id, name, major)
enrollments(id, student_id, course_code)

Input

Sample Data

students

idnamemajor
1MinaCS
2DanielMath
3SofiaDesign

enrollments

idstudent_idcourse_code
11DB101
23WEB201

Output

Expected Output

name
Mina
Sofia

Answer

Check Your Solution

Show Answer and Explanation

Correct Answer

SELECT name
FROM students
WHERE id IN (
  SELECT student_id
  FROM enrollments
)
ORDER BY name;

Explanation

The subquery returns student_id values that exist in enrollments. IN keeps students whose id is one of those values.

Common Mistakes

  • Using = with a subquery that can return multiple rows.
  • Comparing students.id to enrollments.id instead of enrollments.student_id.
  • Using NOT IN, which returns the opposite set.

Concepts

Related Concepts

IN Subquery Relationships Filtering

Next practice

Related Problems