Lecture

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
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