A subquery is a whole query in brackets, used inside another one. The inner one runs and the outer one uses its answer. When the subquery returns one value, it can go anywhere a value can. Products dearer than the average:
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price;
That's better than typing the average in: if prices change, the query is still right. When a subquery returns a list (one column, many rows), use it with IN. Customers with at least one shipped order:
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'shipped')
ORDER BY name;
Returns
name
----
Ana
Ben
Cleo
Dev
Finn
(5 rows)
A subquery can also stand in for a table after FROM. It needs an alias:
SELECT ROUND(AVG(n), 2) AS avg_orders
FROM (SELECT customer_id, COUNT(*) AS n FROM orders GROUP BY customer_id) AS per_customer;
Returns
avg_orders
----------
1.67
(1 row)
EXISTS (subquery) is true if the subquery finds at least one row. The subquery here uses c.id from the outer query, so it's worked out again for each customer; that's called a correlated subquery. SELECT 1 is a habit: EXISTS only cares whether a row exists, not what's in it.
SELECT c.name
FROM customers c
WHERE NOT EXISTS (SELECT 1 FROM orders o WHERE o.customer_id = c.id);
Returns
name
----
Gus
Hana
(2 rows)
One trap: NOT IN with a list that contains a NULL matches nothing at all. "Is Denver not in (NULL, Boston, Austin)?" Denver might be the unknown one, so the answer is unknown, and WHERE drops the row. Customer 6's city is NULL, so this finds nobody, not even Ben in Denver:
SELECT name
FROM customers
WHERE city NOT IN (SELECT city FROM customers WHERE id >= 6);
Returns
name
----
(0 rows)
NOT EXISTS doesn't have this problem, so it's the safer way to ask "has no matching row". Or filter the NULLs out of the list with WHERE city IS NOT NULL inside the subquery.
Practice
Products priced above the average price: name and price. Work the average out in a subquery; don't type the number.