BBampaa

Lessons › SQL › Chapter 5: Combining tables

SQL lesson

Subqueries

A subquery is a question nested inside another question - you get one result first, then feed it straight into the outer query without any manual steps in between. Like doing a quick back-of-envelope calculation before writing your final answer, except the database handles both calculations at once.

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

Example

Answering Benchmark Questions with Subqueries

SELECT order_id, customer_id, revenue
FROM orders
WHERE revenue > (SELECT AVG(revenue) FROM orders)

Result:

order_idcustomer_idrevenue
O2001C101120.5
O2003C103310.75

Step by step

  1. Run the query without AVG so you can see what the unfiltered values look like.
    SELECT order_id, customer_id, revenue
    FROM orders
    WHERE revenue > (SELECT revenue FROM orders);
  2. AVG returns the mean of the values in a column.
    SELECT order_id, customer_id, revenue
    FROM orders
    WHERE revenue > (SELECT AVG(revenue) FROM orders);
  3. AS gives the AVG result a friendly column name so the output reads cleanly.
    SELECT order_id, customer_id, revenue
    FROM orders
    WHERE revenue > (SELECT AVG(revenue) AS avg_result FROM orders);

Practice

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

1. Using orders, write a query to find all rows where revenue is greater than the average revenue across the whole table.
SELECT * FROM orders WHERE revenue > (SELECT AVG(revenue) FROM orders)
2. Using customers, write a query to find all rows where email is greater than the average email across the whole table.
SELECT * FROM customers WHERE email > (SELECT AVG(email) FROM customers)
3. Using products, write a query to find all rows where price is greater than the average price across the whole table.
SELECT * FROM products WHERE price > (SELECT AVG(price) FROM products)
4. Using store_sales, write a query to find all rows where revenue is greater than the average revenue across the whole table.
SELECT * FROM store_sales WHERE revenue > (SELECT AVG(revenue) FROM store_sales)
5. Using employees, write a query to find all rows where salary is greater than the average salary across the whole table.
SELECT * FROM employees WHERE salary > (SELECT AVG(salary) FROM employees)

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