Introduction to Subqueries
What You'll Learn
You'll discover how to nest one SQL query inside another to answer more complex questions in a single statement.
What is a Subquery?
A subquery (also called an inner query or nested query) is a SELECT statement embedded inside another SQL statement. Think of it like solving a math problem in two steps: first you calculate a sub-expression in parentheses, then use that result in the outer calculation.
For example, you might want to find all employees who earn more than the average salary. First you need to calculate the average (step 1), then compare each employee against it (step 2). A subquery lets you do both in one go.
SELECT name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);
The query in parentheses runs first, returning the average salary. The outer query then uses that single value to filter results.
Where Can Subqueries Appear?
Subqueries can be placed in several locations:
- In the WHERE clause (most common) - for filtering based on calculated values
- In the FROM clause - treating the subquery result as a temporary table
- In the SELECT clause - to compute a value for each row
Subqueries vs Joins
While you've already learned that joins combine rows from multiple tables horizontally, subqueries typically filter or compute values first, then use those in the outer query. Sometimes you can solve the same problem with either approach, but subqueries shine when you need to compare against aggregate values or when the logic is more naturally expressed as "find X where Y meets some condition."
Key Takeaway: Subqueries let you nest one SELECT inside another, enabling multi-step logic in a single query—especially useful when filtering against aggregate results or computed values.