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 →Example
Answering Benchmark Questions with Subqueries
SELECT order_id, customer_id, revenue
FROM orders
WHERE revenue > (SELECT AVG(revenue) FROM orders)| order_id | customer_id | revenue |
|---|---|---|
| O2001 | C101 | 120.5 |
| O2003 | C103 | 310.75 |
Step by step
- 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); - 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); - 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
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 →