Subqueries
A subquery is a query inside another query, in brackets. Use it when you need a value that must be worked out first.
A subquery is a query inside another query - for example, "products priced above the average price" needs the average first. Subqueries let you build complex questions out of simple steps, which is easier to write and to check.
A single value
Example
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products);
-- Result:
-- name | price
-- -----------------+------
-- Denim Jeans | 1299
-- Wireless Earbuds | 1499
-- Smart Watch | 3999▶ Try it yourselfA list for IN
Example
SELECT name
FROM customers
WHERE id IN (SELECT customer_id FROM orders WHERE status = 'delivered');
-- Result:
-- name
-- -----------
-- Asha Verma
-- Ravi Kumar
-- Arjun Mehta▶ Try it yourselfEXISTS
EXISTS is true if the subquery returns any row. Here: products that were never ordered.
Example
SELECT name
FROM products p
WHERE NOT EXISTS (SELECT 1 FROM order_items oi WHERE oi.product_id = p.id);
-- Result:
-- name
-- --------
-- Yoga Mat▶ Try it yourselfA subquery as a table
Example
SELECT customer_id, total
FROM (SELECT o.customer_id, SUM(oi.qty * oi.price) AS total
FROM orders o JOIN order_items oi ON oi.order_id = o.id
GROUP BY o.customer_id) AS t
WHERE total > 2000;
-- Result:
-- customer_id | total
-- ------------+------
-- 1 | 4191
-- 2 | 4297
-- 3 | 3999
-- 4 | 2097▶ Try it yourselfThe EXISTS example is a correlated subquery: it uses
p.id from the outer query, so it runs once for each product.Key points
- A subquery is a SELECT inside another statement.
- Use them in WHERE, FROM or SELECT.
- IN and EXISTS test against a subquery's results.
📝 Test yourself
1. Which query finds products dearer than the average?
2. What does NOT EXISTS (subquery) check?
3. Fill in the keyword that checks a list from a subquery:
WHERE id (SELECT customer_id FROM orders)
