Question 1
Retrieve the name and price of products priced higher than the average price of all products.
What is a subquery?
A subquery is a technique for embedding one SQL statement inside another, wrapped in parentheses. Think of it as: "first run the inner query, then use its result in the outer query."
WHERE price > (SELECT AVG(price) FROM products)
A subquery in the WHERE clause
This is handy when you want to compare against an aggregated result. Things like "products above the average price" or "the product matching the maximum value" can be written in one go.
SELECT name, price
FROM products
WHERE price > (
SELECT AVG(price) FROM products
);
A subquery with IN
This is the pattern of "filtering using a list of IDs that satisfy some condition in another table." You can get the same result with a JOIN, but sometimes this reads more naturally.
SELECT * FROM orders
WHERE user_id IN (
SELECT id FROM users WHERE city = '東京'
);
-- '東京' = "Tokyo"
If a subquery like
WHERE price = (SELECT price FROM products WHERE ...) might return more than one row, use IN instead of =. = can only accept a single row and will error out otherwise.
A subquery in the FROM clause (a derived table)
This is useful when you want to further filter a result that's already been aggregated once. For something like "categories whose average price is $200 or more," a derived table can sometimes be a cleaner fit than HAVING.
SELECT cat.category, cat.avg_price
FROM (
SELECT category, AVG(price) AS avg_price
FROM products
GROUP BY category
) cat
WHERE cat.avg_price > 20000;
Analytical queries about comparisons and rankings — "find the sales reps whose sales are above the overall average," "identify users whose spending increased from last month" — rely heavily on subqueries. Once you're comfortable with them, you can write surprisingly complex analysis in a single query.