Subquery in WHERE
Clause
A common use of subqueries is inside the WHERE
clause.
This allows you to filter results based on the output of another query.
Why It's Useful
Subqueries inside WHERE
help you:
- Match dynamic values (like the top user, most common course, etc.)
- Filter without hardcoding
- Write cleaner logic with fewer joins
Think of it like: “Only show users if they appear in this other result.”
Example: Users who selected more than one course
The following query returns users who selected more than one course.
Subquery in WHERE clause
SELECT name
FROM users
WHERE user_id IN (
SELECT user_id
FROM user_courses
GROUP BY user_id
HAVING COUNT(*) > 1
);
Result:
name |
---|
Sofia |
Aisha |
Liam |
These users picked more than one course.
Tips
- Always wrap subqueries in
()
- Use
IN
or comparison operators (=
,>
, etc.) - Watch out for performance on large datasets
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.