What is a Subquery?
A subquery is a SQL query written inside another query.
It allows you to use the result of one query as input for another, making your SQL logic more flexible and powerful.
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 creating temporary tables
- Simplify logic inside
WHERE,FROM, orSELECTclauses
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' );
Here, the subquery in the WHERE clause filters the users table so that only users who selected the Python course are returned.
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