The CASE
statement is one of the most powerful and flexible tools in SQL. It allows conditional logic anywhere in your queryβSELECT
, WHERE
, GROUP BY
, ORDER BY
, and especially within aggregations.
β
General Syntax of CASE
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
π Use Cases of CASE
in Different Clauses
β
1. In SELECT
β Conditional column values
SELECT name,
salary,
CASE
WHEN salary > 100000 THEN 'High'
WHEN salary > 50000 THEN 'Medium'
ELSE 'Low'
END AS salary_band
FROM employees;
π Labeling or categorizing data based on conditions.
β
2. In WHERE
β Conditional filtering (less common)
SELECT *
FROM orders
WHERE
CASE
WHEN status = 'pending' THEN amount > 100
ELSE TRUE
END;
π Used sparingly, but can apply complex filters dynamically.
β
3. In ORDER BY
β Conditional sort logic
SELECT name, status
FROM tasks
ORDER BY
CASE
WHEN status = 'urgent' THEN 1
WHEN status = 'high' THEN 2
ELSE 3
END;
π Custom ordering of categorical values.
β 4. In Aggregation β Conditional counting or summing
a. Count by condition:
SELECT
department,
COUNT(*) AS total_employees,
COUNT(CASE WHEN gender = 'Male' THEN 1 END) AS male_count,
COUNT(CASE WHEN gender = 'Female' THEN 1 END) AS female_count
FROM employees
GROUP BY department;
b. Sum conditionally:
SELECT
department,
SUM(CASE WHEN salary > 50000 THEN salary ELSE 0 END) AS high_earner_total
FROM employees
GROUP BY department;
c. Multiple category aggregation:
SELECT
product_type,
SUM(CASE WHEN status = 'delivered' THEN 1 ELSE 0 END) AS delivered_count,
SUM(CASE WHEN status = 'cancelled' THEN 1 ELSE 0 END) AS cancelled_count
FROM orders
GROUP BY product_type;
β
5. In GROUP BY
β Grouping based on a derived value
SELECT
CASE
WHEN age < 18 THEN 'Minor'
WHEN age BETWEEN 18 AND 60 THEN 'Adult'
ELSE 'Senior'
END AS age_group,
COUNT(*)
FROM users
GROUP BY
CASE
WHEN age < 18 THEN 'Minor'
WHEN age BETWEEN 18 AND 60 THEN 'Adult'
ELSE 'Senior'
END;
π You must repeat the CASE in GROUP BY unless you use a subquery or CTE.
β
6. Nested CASE
SELECT name,
CASE
WHEN country = 'India' THEN
CASE
WHEN city = 'Delhi' THEN 'North'
WHEN city = 'Mumbai' THEN 'West'
ELSE 'Other'
END
ELSE 'International'
END AS region
FROM users;
π Useful for multi-layered logic.
π§ Summary Table
Location | Example Use Case |
---|---|
SELECT | Categorize values, label based on logic |
WHERE | Conditional filters |
ORDER BY | Custom sort order |
GROUP BY | Group by derived buckets (like age, band) |
Aggregation | Conditional SUM , COUNT , AVG etc. |
Leave a Reply