A subquery is a query nested inside another query. It can appear in:
WHERE:WHERE Price > (SELECT AVG(Price) FROM Products)FROM: as a temporary table (a "derived table").SELECT: to calculate a value per row (a "correlated subquery").
Queries inside queries.
✍️ 3 exercises + code challenge in this lessonA subquery is a query nested inside another query. It can appear in:
WHERE: WHERE Price > (SELECT AVG(Price) FROM Products)FROM: as a temporary table (a "derived table").SELECT: to calculate a value per row (a "correlated subquery").Mastering SQL Subqueries helps you write clean and reliable SQL code. Follow standard conventions, test edge cases, and keep logic simple. Try running the code example below and complete the exercises to build confidence.
-- Products priced above average
SELECT ProductName, Price FROM Products
WHERE Price > (SELECT AVG(Price) FROM Products);
-- Number of orders per customer, as a column
SELECT CustomerName,
(SELECT COUNT(*) FROM Orders o WHERE o.CustomerID = c.CustomerID) AS OrderCount
FROM Customers c
ORDER BY OrderCount DESC;
Check what you learned in “SQL Subqueries”.
Compare with the average price.
WHERE Price > ( AVG(Price) FROM Products)
Where can a subquery appear?
Select the ProductName of the most expensive product using a subquery with MAX.
Free sign-in required · Google login available
Stuck on something?
Ask the community in the CodesInTech forum.
Need a developer?
Learning on your own is great — and when you need professional help, our team builds custom software, websites and mobile apps for clients worldwide.
Explore Our Services