TECHNOLOGIESTieInn Technologies

CASE WHEN

SQL · 15 questions

Short notes

Key idea

CASE WHEN is SQL's if/else. It returns a value per row, so you can label, bucket or conditionally count.

Syntax

CASE
  WHEN amount >= 5000 THEN 'large'
  WHEN amount >= 1000 THEN 'medium'
  ELSE 'small'
END AS size

Conditions are tried top to bottom; the first true one wins.

Example

Count delivered and cancelled orders in one pass:

SELECT city,
       SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered,
       SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled
FROM orders
GROUP BY city;

This "pivot with CASE" is one of the most asked interview patterns.

Traps

  • Order matters. Put the narrowest condition first, or >= 1000 will catch everything above 5000 too.
  • No ELSE means NULL for rows that match nothing.
  • All branches should return the same type (don't mix text and numbers).
  • CASE x WHEN NULL never matches; use CASE WHEN x IS NULL.

Want the full lesson with step-by-step examples, a project and a certificate? SQL course, ₹120 →

Questions

Open in Code Lab5 free questions
5 questions

    CASE WHEN

  1. Question 1easy

    A CASE has no ELSE, and a row matches none of the WHEN conditions. What does it return for that row?

  2. CASE WHEN

  3. Question 2medium

    6 products cost under ₹700, and 9 cost under ₹1,000. What does this return?

    SELECT COUNT(*) FROM products
    WHERE CASE
            WHEN price < 1000 THEN 'cheap'
            WHEN price < 700  THEN 'very cheap'
            ELSE 'other'
          END = 'very cheap';
  4. CASE WHEN

  5. Question 3medium

    What does this return?

    SELECT SUM(CASE WHEN status IN ('cancelled', 'returned') THEN 1 ELSE 0 END)
    FROM orders;
  6. CASE WHEN

  7. Question 4medium

    Which correctly labels customers with no city as 'Unknown'?

  8. CASE WHEN

  9. Question 5hard

    There are 80 orders and 12 are cancelled. What does this return?

    SELECT COUNT(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END)
    FROM orders;

10 more questions on this topic, with hints, and tests

Sign up free for 21 days of every question and test.