Nishaglobal Education logo

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.

Lesson 11 of 1230 minQuiz: 4 questions

🎯 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
  1. What you'll learn and why it matters
  2. A subquery that returns one value
  3. A subquery that returns a list: IN and NOT IN
  4. CASE: if-then-else inside a query
  5. Counting conditions with CASE
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

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:

SQL
SELECT AVG(price) AS average_price FROM products;

Result: 1 row

Query result
average_price
394.625

Now put that query, in brackets, where you would have typed the number:

SQL
SELECT name, price
FROM products
WHERE price > (SELECT AVG(price) FROM products)
ORDER BY price DESC;

Result: 3 rows

Query result
nameprice
Desk Lamp1200
Python Basics Book450
Water Bottle399

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)?

SQL
SELECT name, country
FROM customers
WHERE customer_id IN (SELECT customer_id FROM orders WHERE product_id = 3);

Result: 3 rows

Query result
namecountry
Asha PatelIndia
Meera NairIndia
Li WeiSingapore

NOT IN gives the opposite. This is another way to find customers with no orders:

SQL
SELECT name, joined_on
FROM customers
WHERE customer_id NOT IN (SELECT customer_id FROM orders);

Result: 2 rows

Query result
namejoined_on
Sara Lopez2025-06-19
Kofi Mensah2025-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:

SQL
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

Query result
namepriceprice_band
Gel Pens (pack of 5)90Budget
Notebook A5120Budget
Coffee Mug249Standard
USB-C Cable299Standard
SQL Pocket Guide350Standard
Water Bottle399Standard
Python Basics Book450Standard
Desk Lamp1200Premium
PartMeaning
CASEStart of the decision
WHEN condition THEN valueIf this is true, use this value. Checked top to bottom; the first true one wins.
ELSE valueUsed when no WHEN is true. Without ELSE you get NULL.
END AS price_bandEnd 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:

SQL
SELECT COUNT(*) AS orders,
  SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders;

Result: 1 row

Query result
orderscancelled
152

Practice

Guided exercise

The most expensive product

Use a subquery with MAX to show the name and price of the most expensive product.

  1. Write the inner query: SELECT MAX(price) FROM products.
  2. Use it in WHERE price = (...).
Show the solution
Solution
SELECT name, price
FROM products
WHERE price = (SELECT MAX(price) FROM products);

Result: 1 row

Query result
nameprice
Desk Lamp1200

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
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

Query result
order_idstatuscounts_as_sale
5deliveredYes
6cancelledNo
7deliveredYes
8shippedYes

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 with IN / NOT IN.
  • CASE WHEN ... THEN ... ELSE ... END labels 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. 1. In `WHERE price > (SELECT AVG(price) FROM products)`, what runs first?

  2. 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. 3. What does `SUM(CASE WHEN status = 'shipped' THEN 1 ELSE 0 END)` calculate?

  4. 4. What happens if a CASE has no ELSE and no WHEN matches?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.