Part 06 / Topic 1 of 8
Scalar subqueries
A query that returns exactly one value can stand anywhere a value stands — wrapped in parentheses. Which products cost more than the average product?
SELECT name, price,
(SELECT round(avg(price), 2) FROM products) AS avg_price
FROM products
WHERE price > (SELECT avg(price) FROM products)
ORDER BY price DESC;
name | price | avg_price
---------------+---------+-----------
Laptop Pro 14 | 1200.00 | 369.80
Laptop Air 13 | 950.00 | 369.80
Phone X | 799.00 | 369.80
Phone Lite | 399.00 | 369.80
(4 rows)
The inner SELECT avg(price) runs first (conceptually), produces one number, and the outer query uses it like a literal. You already met this in the Stage 1 project's percentage trick — now it has its name.
If a scalar subquery returns more than one row, Postgres raises an error; if it returns no rows, it yields NULL. Both behaviours are exactly what "this must be one value" implies.
🧪 Quick quiz — answer from memory, then check.
- What makes a subquery "scalar"?
- What does a scalar subquery yield when it finds no rows?
Show the answers
- It returns a single value (one row, one column), so it can stand wherever a value can.
- NULL — and more than one row is an error.
Exercise 1: Pricier than average
What to do: Products costing more than the average product, priciest first — without hard-coding the average.
Sample output:
name | price
---------------+---------
Laptop Pro 14 | 1200.00
Laptop Air 13 | 950.00
Phone X | 799.00
Phone Lite | 399.00
(4 rows)
💡 Hint: a scalar subquery in the WHERE.
Show the solution to Exercise 1
-- Exercise 1: Pricier than average
SELECT name, price
FROM products
WHERE price > (SELECT avg(price) FROM products)
ORDER BY price DESC;