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 →Example
A query inside a query
SELECT *
FROM orders
WHERE revenue > (SELECT AVG(revenue) FROM orders)| order_id | customer_id | revenue | category |
|---|---|---|---|
| O2001 | C101 | 120.5 | Electronics |
| O2003 | C103 | 310.75 | Electronics |
Step by step
- 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) - 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
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 →