Subqueries and CASE: questions inside questions
Use a SQL subquery to compare with an average or filter with IN, and use CASE expressions to label rows and count conditions inside aggregates.
π― By the end of this lesson you will be able to:
- Use a subquery that returns one value, such as an average
- Filter with IN and NOT IN using a subquery that returns a list
- Label rows and count conditions with CASE
Outline
What you'll learn and why it matters
Some questions need an answer to another question first. βWhich products cost more than average?β needs the average before you can compare. A subquery is a query inside another query that provides that first answer. CASE lets a query make decisions, like if in a programming language, so you can sort rows into bands or count only some rows.
A subquery that returns one value
First, the average price on its own:
SELECT AVG(price) AS average_price FROM products;Result: 1 row
| average_price |
|---|
| 394.625 |
Now put that query, in brackets, where you would have typed the number:
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;Result: 3 rows
| name | price |
|---|---|
| Desk Lamp | 1200 |
| Python Basics Book | 450 |
| Water Bottle | 399 |
The database runs the inner query first (394.625), then uses the result in the outer WHERE. If prices change, the query still gives the right answer, which a typed-in number would not.
A subquery that returns a list: IN and NOT IN
A subquery that returns one column of several rows works with IN. Which customers bought the Python book (product 3)?
SELECT name, country
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE product_id = 3);Result: 3 rows
| name | country |
|---|---|
| Asha Patel | India |
| Meera Nair | India |
| Li Wei | Singapore |
NOT IN gives the opposite. This is another way to find customers with no orders:
SELECT name, joined_on
FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);Result: 2 rows
| name | joined_on |
|---|---|
| Sara Lopez | 2025-06-19 |
| Kofi Mensah | 2025-09-14 |
CASE: if-then-else inside a query
CASE checks conditions in order and returns the value for the first one that is true, just like if/elif/else:
SELECT name, price,
CASE
WHEN price < 200 THEN 'Budget'
WHEN price < 500 THEN 'Standard'
ELSE 'Premium'
END AS price_band
FROM products
ORDER BY price;Result: 8 rows
| name | price | price_band |
|---|---|---|
| Gel Pens (pack of 5) | 90 | Budget |
| Notebook A5 | 120 | Budget |
| Coffee Mug | 249 | Standard |
| USB-C Cable | 299 | Standard |
| SQL Pocket Guide | 350 | Standard |
| Water Bottle | 399 | Standard |
| Python Basics Book | 450 | Standard |
| Desk Lamp | 1200 | Premium |
| Part | Meaning |
|---|---|
CASE | Start of the decision |
WHEN condition THEN value | If this is true, use this value. Checked top to bottom; the first true one wins. |
ELSE value | Used when no WHEN is true. Without ELSE you get NULL. |
END AS price_band | End of the decision, and the column's name |
Counting conditions with CASE
Put a CASE that gives 1 or 0 inside SUM to count only the rows you care about, next to the overall total:
SELECT COUNT(*) AS orders,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;Result: 1 row
| orders | cancelled |
|---|---|
| 15 | 2 |
Practice
Guided exercise
The most expensive product
Use a subquery with MAX to show the name and price of the most expensive product.
- Write the inner query:
SELECT MAX(price) FROM products. - Use it in
WHERE price = (...).
Show the solution
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);Result: 1 row
| name | price |
|---|---|
| Desk Lamp | 1200 |
How to get there: Unlike ORDER BY price DESC LIMIT 1, this also returns every product if two share the top price.
Your turn
Does it count as a sale?
For orders 5 to 8, show the order id, status and a column counts_as_sale that is No for cancelled orders and Yes otherwise.
Show the solution
SELECT order_id, status,
CASE WHEN status = 'cancelled' THEN 'No' ELSE 'Yes' END AS counts_as_sale
FROM orders
WHERE order_id BETWEEN 5 AND 8;Result: 4 rows
| order_id | status | counts_as_sale |
|---|---|---|
| 5 | delivered | Yes |
| 6 | cancelled | No |
| 7 | delivered | Yes |
| 8 | shipped | Yes |
How to get there: A CASE can fit on one line when it has a single WHEN. Shipped orders still count as sales; only cancelled ones do not.
Common mistakes
A single-value subquery that returns several rows
You see: Wrong results (SQLite quietly uses the first row; other databases give an error)
Fix: Make sure a subquery used with = or > returns exactly one value, e.g. with an aggregate.
Forgetting the brackets around a subquery
You see: near "SELECT": syntax error
Fix: Wrap every subquery in ( ).
Forgetting END in a CASE
You see: near "FROM": syntax error
Fix: Every CASE finishes with END.
WHEN conditions in the wrong order
You see: Everything falls into the first band
Fix: Put the narrowest condition first, as with if/elif.
Recap
- A subquery is a query in brackets inside another query; the inner one runs first.
- Use a one-value subquery with
=,>and so on; a one-column list withIN/NOT IN. CASE WHEN ... THEN ... ELSE ... ENDlabels rows like if/elif/else.SUM(CASE WHEN condition THEN 1 ELSE 0 END)counts only matching rows.
Key terms
- Subquery
- A query written inside another query, in brackets.
- CASE expression
- SQL's if-then-else, which returns a value based on conditions.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. In `WHERE price > (SELECT AVG(price) FROM products)`, what runs first?
2. What does this CASE give for a price of 200? CASE WHEN price < 200 THEN 'Budget' WHEN price < 500 THEN 'Standard' ELSE 'Premium' END
3. What does `SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END)` calculate?
4. What happens if a CASE has no ELSE and no WHEN matches?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.