SQL Subqueries, explained
A subquery is a query in brackets that runs inside another query. It can produce a single value to compare against, or a list of values to check with IN.
A CTE (common table expression) does the same job with a name: WITH name AS (...) runs first, and the main query can use it like a table. CTEs make long queries easier to read.
Examples
1. Compare with an average
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);The inner query returns one number, the average price.
2. Name a step with WITH
WITH spend AS (
SELECT customer_id, SUM(total) AS total_spent
FROM orders
GROUP BY customer_id
)
SELECT * FROM spend WHERE total_spent > 400;The CTE builds totals once, then the main query filters them.
Practice Subqueries
4 questions, easiest first. Your progress is saved on this device.
- โAbove averagemedium
- ๐Customers who cancelledmedium
- ๐Big spenders with a CTEhard
- ๐Above their team averagehard