Subqueries
SQL · 14 questions
Short notes
Key idea
A subquery is a query inside another query. Use it when one answer depends on another: "orders above the average", "customers who bought X".
Syntax
-- a single value
WHERE amount > (SELECT AVG(amount) FROM orders)
-- a list
WHERE customer_id IN (SELECT customer_id FROM vip)
-- a table
FROM (SELECT ... ) AS t
-- correlated: runs per outer row
WHERE EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.customer_id)
Example
Products priced above their own category's average:
SELECT p.name, p.price
FROM products p
WHERE p.price > (SELECT AVG(price) FROM products x
WHERE x.category = p.category);
Traps
- A subquery after
=must return one row. If it returns several, the query fails; useIN. NOT INwith a NULL in the subquery returns nothing. PreferNOT EXISTS.- Give a subquery in
FROMan alias; several databases refuse it without one. - Deep nesting is hard to read. If you nest more than twice, switch to a CTE.
Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →
- Question 1easy
Which query finds products priced above the average price?
- Question 2medium
The average product price is about ₹1,704. What does this return?
SELECT COUNT(*) FROM products WHERE price > (SELECT AVG(price) FROM products);
- Question 3medium
What does this return?
SELECT COUNT(*) FROM orders WHERE customer_id IN ( SELECT customer_id FROM customers WHERE city = 'Chennai' );
- Question 4hard
SELECT * FROM customers WHERE customer_id NOT IN (SELECT referred_by FROM signups). The subquery returns some NULLs. What happens? - Question 5hard
10 customers live in Chennai. What happens when you run
SELECT COUNT(*) FROM orders WHERE customer_id = (SELECT customer_id FROM customers WHERE city = 'Chennai');?
Subqueries
Subqueries
Subqueries
Subqueries
Subqueries
9 more questions on this topic, with hints, and tests
Sign up free for 21 days of every question and test.