CASE Expression
Overview
The CASE expression implements conditional if-then-else logic directly inside SQL queries, enabling dynamic data classification.
Learning Objectives
- Implement Simple
CASEswitch checks. - Build range conditional validations using Searched
CASE. - Nest
CASEstructures inside aggregations for conditional totals.
Detailed Concept Explanation
SQL's CASE works like standard conditional structures in programming languages. It evaluates expressions in order, returning the output of the first TRUE condition.
Simple CASE
Compares a column or expression against fixed matching values:
CASE role_code
WHEN 1 THEN 'Admin'
WHEN 2 THEN 'Manager'
ELSE 'User'
END
Searched CASE
Evaluates completely separate range/logical predicates:
CASE
WHEN price > 100 THEN 'Premium'
WHEN price BETWEEN 50 AND 100 THEN 'Standard'
ELSE 'Budget'
END
Code Examples
SQL
-- Classify employee experience groups
SELECT name, salary,
CASE
WHEN salary >= 100000 THEN 'Tier 1'
WHEN salary >= 60000 THEN 'Tier 2'
ELSE 'Tier 3'
END AS salary_tier
FROM employees;
-- Count items by status category (Conditional Aggregation)
SELECT
SUM(CASE WHEN status = 'Shipped' THEN 1 ELSE 0 END) AS shipped_count,
SUM(CASE WHEN status = 'Pending' THEN 1 ELSE 0 END) AS pending_count
FROM orders;
Best Practices
- Include ELSE: Always provide an
ELSEfallback inside yourCASEstatement. If no conditions match andELSEis missing, the expression returnsNULL. - Avoid Deep Nesting: Deeply nested
CASEstatements degrade performance and are hard to debug. Keep conditions modular.
Interview Perspective
Note
Interview Question: What is Conditional Aggregation in SQL?
It's the practice of nesting CASE statements inside aggregate functions (like SUM or COUNT). This allows you to pivot rows or compute multiple conditional aggregations in a single query pass without joining the table multiple times.
Interactive Challenges
Summary
CASE statements enable conditional data styling and routing, making it easy to categorize attributes and write conditional sums.