What is a subquery?
A subquery is a query written inside another SQL query. It is used to retrieve data that will be used by the main query.
Syntax
SELECT column_name
FROM table_name
WHERE column_name = (
SELECT column_name
FROM another_table
);Example
Suppose you have an Employees table.
Get Nivethabaskar’s stories in your inbox
Join Medium for free to get updates from this writer.
To find employees who earn more than the average salary:
SELECT name, salary
FROM Employees
WHERE salary > (
SELECT AVG(salary)
FROM Employees
);How it works
- The inner query (subquery) calculates the average salary.
- The outer query selects employees whose salary is greater than that value.
Types of Subqueries
- Single-row subquery — returns one value
- Multiple-row subquery — returns multiple values
- Correlated subquery — depends on the outer query
- Nested subquery — subquery inside another subquery
Advantages
- Simplifies complex queries
- Improves readability
- Helps perform calculations before the main query executes
Simple Definition
A subquery is a query inside another query used to help the main query get the required result.







