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
Quiz
0 / 1
What is a primary advantage of using subqueries in the WHERE clause of an SQL statement?
To increase the speed of query execution.
To prevent SQL injection attacks.
To filter results based on the output of another query.
To eliminate the need for table joins.
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Tables
Execution Result