BBampaa

Lessons › SQL › Chapter 5: Joins, subqueries and CTEs

SQL lesson

Subqueries

A subquery is a query inside another query. SQL runs the inside one first, then uses its answer in the outside one. It's useful when you need a number you don't know yet, like the average. Instead of working it out and typing it in, you let SQL work it out.

Try this lesson free →
About 5–10 minutes · no sign-up needed

Example

A query inside a query

SELECT *
FROM orders
WHERE revenue > (SELECT AVG(revenue) FROM orders)

Result:

order_idcustomer_idrevenuecategory
O2001C101120.5Electronics
O2003C103310.75Electronics

Step by step

  1. The inside query, in brackets, works out one number first: the average. The outside query compares each row with it.
    SELECT * FROM orders WHERE revenue > (SELECT AVG(revenue) FROM orders)
  2. The inside query can give back a list. IN keeps the rows on it; NOT IN keeps the ones that aren't.
    SELECT * FROM orders WHERE customer_id IN (SELECT customer_id FROM customers WHERE city = 'Lagos')

Practice

Try each one in your head first, then open the answer.

1. Using orders, show every order with revenue above the average revenue.
SELECT * FROM orders WHERE revenue > (SELECT AVG(revenue) FROM orders)
2. Using orders, show the order with the highest revenue.
SELECT * FROM orders WHERE revenue = (SELECT MAX(revenue) FROM orders)
3. Using products, show every product cheaper than the average price.
SELECT * FROM products WHERE price < (SELECT AVG(price) FROM products)
4. Using store_sales, show the sale with the highest revenue.
SELECT * FROM store_sales WHERE revenue = (SELECT MAX(revenue) FROM store_sales)

Learn it by doing. This lesson is a short hands-on level on Bampaa: see it work, then build and write it yourself, with instant feedback.

Try this lesson free →
About 5–10 minutes · no sign-up needed