Subquery in WHERE Clause
One of the most common uses 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 results without hardcoding values
- Simplify queries without relying on extra joins
You can think of it as: “Return a row only if it exists in another 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 parentheses
() - Use
INor 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.