What is a Subquery?
A subquery
is a SQL query written inside another query.
It lets you use one query's result as input for another — making your SQL logic smarter and more dynamic.
Subqueries are also called nested queries or inner queries.
Why Use Subqueries?
You can use subqueries when you want to:
- Filter or compare based on dynamic results
- Avoid repeating steps or temporary tables
- Simplify logic inside
WHERE
,FROM
, orSELECT
clauses
Tip: Always wrap subqueries in parentheses.
Example: Users who selected the Python course
In this example, we work with two tables:
users
: contains user IDs and namesuser_courses
: tracks which courses each user selected
To find users who selected the Python course, we can use a subquery like this:
Subquery to find users of the Python course
SELECT name FROM users WHERE user_id IN ( SELECT user_id FROM user_courses WHERE course = 'Python' );
The subquery in the WHERE
clause filters the users
table to only include users who have selected the Python course.
Result:
name |
---|
Sofia |
Ethan |
Liam |
Quiz
0 / 1
What is a Subquery?
A subquery is a SQL query written another query.
above
inside
below
beside
Lecture
AI Tutor
Design
Upload
Notes
Favorites
Help
Code Editor
Run
Generate
Tables
Execution Result