SQL Subqueries

Queries inside queries.

✍️ 3 exercises + code challenge in this lesson

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").

Key Takeaways: SQL Subqueries

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.

SQL Subqueries Code Example

SQL
-- 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;
Free sign-in required · Google login available

SQL Subqueries Practice Exercises

Check what you learned in “SQL Subqueries”.

/ 3 solved
Fill in the blank

Compare with the average price.

WHERE Price > ( AVG(Price) FROM Products)
✓ Correct! Not quite. Try again.
Multiple choice

Where can a subquery appear?

✓ Correct! Not quite. Try again.
Code challenge

Select the ProductName of the most expensive product using a subquery with MAX.

Write the code in the live editor. Your answer is checked automatically.

Free sign-in required · Google login available

to save your exercise progress.
Finished this lesson?
Mark it complete to track your progress.

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