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
| id | name | major |
|---|---|---|
| 1 | Mina | CS |
| 2 | Daniel | Math |
| 3 | Sofia | Design |
enrollments
| id | student_id | course_code |
|---|---|---|
| 1 | 1 | DB101 |
| 2 | 3 | WEB201 |
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