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 |
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.