SQL CASE ELSE
Supplies a fallback value for rows that don't match any WHEN condition — without it, non-matching rows silently become NULL.
What & Why
ELSE value goes right before END, and it's what a row falls back to when none of the WHEN conditions above it matched. Without an explicit ELSE, that fallback is always NULL — which the CASE WHEN lesson touched on briefly. This lesson is about replacing that default with something more useful.
See How It Works
Product wants every feedback rating classified, including ratings outside the positive rule.
| id | user_id | feature_id | rating | nps_score | comment | created_at |
|---|---|---|---|---|---|---|
| 1 | 101 | 1 | 5 | 9 | Clear and useful | 2024-01-25 12:15:00+00 |
| 2 | 102 | 2 | 4 | NULL | Export worked well | 2024-02-20 15:40:00+00 |
| 3 | 103 | 1 | 4 | 7 | Helpful setup flow | 2024-03-18 09:05:00+00 |
| 4 | 104 | 3 | 3 | NULL | Needs clearer timing | 2024-04-08 17:30:00+00 |
SELECT
id AS feedback_id,
rating,
CASE WHEN rating >= 4 THEN 'positive' ELSE 'not positive' END AS rating_class
FROM product.feedback
ORDER BY feedback_id;| feedback_id | rating | rating_class |
|---|---|---|
| 1 | 5 | positive |
| 2 | 4 | positive |
| 3 | 4 | positive |
| 4 | 3 | not positive |
ELSE gives the final feedback row an explicit fallback label.
Practice this concept
Product wants every feedback rating classified, including ratings outside the positive rule.
productPrefix tables with product.table_name.
feedback_idratingrating_classproduct.feedback| Column | Type |
|---|---|
| id | integer |
| user_id | integer |
| feature_id | integer |
| rating | integer |
| nps_score | integer |
| comment | text |
| created_at | timestamp with time zone |
| moderation_bucket | text |
Sign up free to try it on a real business scenario