Home › Learn › SQL › Joins

Subqueries

Lesson 20 of 26. Use one query's answer inside another.

A query in parentheses can stand in for a value or a list. "Products above the average price" needs the average first: WHERE price > (SELECT AVG(price) FROM products). A subquery that returns one column can feed IN: WHERE id IN (SELECT product_id FROM orders) finds products that were ever ordered, and NOT IN the ones that never were.

Many subqueries can be rewritten as joins and vice versa; use whichever reads more naturally. Subqueries in the FROM clause act as temporary tables.

SELECT name FROM products WHERE id NOT IN (SELECT product_id FROM orders);

Your task

Show the name and price of every product priced above the average product price.

Hint 1

(SELECT AVG(price) FROM products)

Show the solution
SELECT name, price FROM products WHERE price > (SELECT AVG(price) FROM products);

    Runs SQLite compiled to WebAssembly in this tab; the database is rebuilt before every run.