Python SQL CASE: Conditional Expressions & Data Transposition
The `CASE` expression is SQL's built-in `if-then-else` decision structure. It evaluates a sequence of conditional clauses and returns the result of the first matching `WHEN` branch. It can be used anywhere expressions are valid (SELECT, WHERE, ORDER BY, GROUP BY).
"`CASE` is like an automated grading machine: input a numerical score (95), test against tier thresholds (>= 90: "A", >= 80: "B"), and output a categorical letter grade."
Deep Dive: How It Works
Searched CASE: `CASE WHEN condition1 THEN val1 WHEN condition2 THEN val2 ELSE default END`. Highly flexible, supports complex boolean logic.
Simple CASE: `CASE status WHEN 'P' THEN 'Pending' WHEN 'C' THEN 'Completed' ELSE 'Unknown' END`. Matches equality against a single target variable.
Pivot / Transposition Pattern: Combining `SUM(CASE WHEN month = 'Jan' THEN sales ELSE 0 END)` turns row data into columnar spreadsheet layouts.
Syntax Blueprint
SELECT
name,
score,
CASE
WHEN score >= 90 THEN 'Excellent'
WHEN score >= 75 THEN 'Good'
ELSE 'Needs Improvement'
END AS performance_rating
FROM students;CASE evaluates conditions in top-down order and returns the first matching branch.
Core Rules to Remember



Common Beginner Traps & How to Fix Them
Forgetting the `END` keyword at the conclusion of a CASE block.Why it happens: Syntax error: every CASE statement must terminate with `END`.
How to fix: Pair every `CASE` with a closing `END`.
Live Interactive Example
Hit Run Code to see it liveYour Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Categorize Numbers with CASE
Select `val`, `CASE WHEN val >= 50 THEN 'Pass' ELSE 'Fail' END AS status` from `scores`.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.