What is a subquery?
- SQL course
- Intermediate
- Lesson 47/115
- 4 min
Run a query inside another query.
What is a subquery?
A subquery is a query inside another query. It is wrapped in parentheses.
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);This query returns products above the average.
name is selected from products. WHERE keeps only the rows where price > (SELECT AVG(price) FROM products) holds.
What is a subquery? — details
The subquery runs first and feeds its result to the outer query. It enables nested queries.
For example, WHERE price > (SELECT AVG(price) FROM products) computes the average first, then returns products above it.
Practice What is a subquery?
Find products priced above average using a subquery.
Starter code
-- above average
SELECT name FROM products
WHERE price >Sample solution
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);Expected output
name Laptop Telefon
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is a subquery inside?
- Curly braces
- Parentheses Correct answer
- Square brackets
- Quotes
Explanation: A subquery is wrapped in parentheses.
2 Add parentheses
SELECT name FROM products
WHERE price > ____SELECT AVG(price) FROM products);
SELECT name FROM products
WHERE price > (SELECT AVG(price) FROM products);
Explanation: A subquery is always written inside parentheses.
3 What is a subquery: match the terms
| Term | Meaning |
|---|---|
subquery |
inner query |
parentheses |
grouping |
SELECT |
select |
WHERE |
filter |