A subquery is a query that is nested inside another query. It is used to retrieve data that will be used in the main query.
When students first learn SQL, they often write simple queries that ask the database for one set of information at a time. But as our questions become more complex, we sometimes need to use the result of one query inside another.
This is where the idea of a subquery becomes important.
A subquery is a query written inside another query.
It is like asking the database a smaller question first, and then using that answer to help solve a bigger question.
I often explain it like this in class:
Imagine you want to find the tallest student in a school. First, you would find the tallest height. Then, you would find the student who has that height.
These two steps together resemble how a subquery works.
Formal Definition
A subquery (also called an inner query or nested query) is a SELECT statement placed inside another SQL statement—usually inside SELECT, INSERT, UPDATE, DELETE, or in the WHERE clause.
Simple Example
Let’s say we want to find the employees who earn more than the average salary.
First question:
“What is the average salary?”
Second question:
“Which employees earn more than that?”
In SQL:
SELECT EmpName, Salary
FROM Employees
WHERE Salary > (SELECT AVG(Salary) FROM Employees);
Here:
- The inner query
(SELECT AVG(Salary)…)is the subquery - The outer query retrieves employees earning above that value
Where Are Subqueries Used?
Subqueries are commonly used to:
- Filter data using another result
- Compare values
- Check existence of related rows
- Replace complex joins when readability is important
- Perform step-by-step logical thinking inside one query
Types of Subqueries
Although you don’t need to memorize all types at the beginning, it’s good to know:
- Single-value subquery – returns one value
- Multiple-row subquery – returns multiple rows
- Multiple-column subquery – returns multiple columns
- Correlated subquery – runs once for each row of the outer query
Why Do We Use Subqueries?
Subqueries help us:
- Break complex logic into smaller steps
- Write readable queries
- Avoid temporary tables
- Make decisions based on dynamic data
In short,
A subquery is a query inside another query, used when the result of one question helps answer a larger question.