Concept Flow - Nested CASE expressions
Start CASE
Evaluate Outer CASE Condition
Return
Return
End
The outer CASE checks a condition; if false, it evaluates an inner CASE expression before returning a result.
SELECT CASE WHEN score >= 90 THEN 'A' ELSE CASE WHEN score >= 80 THEN 'B' ELSE 'C' END END AS grade FROM students;
| Step | score | Outer CASE Condition (score >= 90) | Outer CASE Result | Inner CASE Condition (score >= 80) | Inner CASE Result | Final grade |
|---|---|---|---|---|---|---|
| 1 | 95 | True | 'A' | N/A | N/A | 'A' |
| 2 | 85 | False | Evaluate Inner CASE | True | 'B' | 'B' |
| 3 | 75 | False | Evaluate Inner CASE | False | 'C' | 'C' |
| 4 | 90 | True | 'A' | N/A | N/A | 'A' |
| 5 | 80 | False | Evaluate Inner CASE | True | 'B' | 'B' |
| 6 | 70 | False | Evaluate Inner CASE | False | 'C' | 'C' |
| Exit | N/A | N/A | All rows processed | N/A | N/A | Grades assigned |
| Variable | Start | After 1 | After 2 | After 3 | After 4 | After 5 | After 6 | Final |
|---|---|---|---|---|---|---|---|---|
| score | N/A | 95 | 85 | 75 | 90 | 80 | 70 | N/A |
| Outer CASE Result | N/A | 'A' | Evaluate Inner CASE | Evaluate Inner CASE | 'A' | Evaluate Inner CASE | Evaluate Inner CASE | N/A |
| Inner CASE Result | N/A | N/A | 'B' | 'C' | N/A | 'B' | 'C' | N/A |
| Final grade | N/A | 'A' | 'B' | 'C' | 'A' | 'B' | 'C' | N/A |
Nested CASE expressions let you put one CASE inside another. Outer CASE checks a condition first. If false, inner CASE runs to check more conditions. Returns the first true condition's result. Useful for multi-level decision making in SQL.