All SQL topics
SQL TOPIC

SQL subqueries: use one answer inside another

A subquery is a query inside a query, for example "products priced above the average".

WHERE price > (SELECT AVG(price) FROM products) compares each row with a single computed value.

IN (SELECT customer_id FROM orders) checks membership in a list that another query produces.

Worked example

Which products cost more than the average product?

SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;
Result on the sample data
nameprice
14-inch laptop1199
Mini PC549
Standing desk499
Ergonomic chair389
27-inch monitor329

Common mistakes

  • Using = with a subquery that returns several rows.
  • Using NOT IN with a list that contains NULL, which returns nothing.