MyMisPal
← SQL lessons
Lesson 9 of 12

Subqueries

Sometimes you need a computed value to compare against. Instead of computing it separately and copying it, put that query in brackets inside the main one:

SQL
SELECT first_name, salary
FROM employees
WHERE salary > (SELECT AVG(salary) FROM employees);

A subquery can also return a list, used with IN:

SQL
SELECT name
FROM customers
WHERE customer_id IN (
  SELECT customer_id FROM orders WHERE status = 'Pending'
);
Watch outMany subqueries can be rewritten as joins and vice versa. Choose whichever reads more clearly.

Exercises

Exercise 1

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

Exercise 2

Show the name of products never ordered, using NOT IN.

Spotted a mistake on this page, or have an idea to improve the site?