CASE Expressions
The CASE expression allows you to add conditional logic to SQL queries.
It works like IF or SWITCH statements in programming languages. You can return different values depending on conditions.
Syntaxβ
The CASE expression evaluates conditions in order and returns the first matching result.
CASE syntax
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END
CASE can be used inside SELECT, ORDER BY, WHERE, and even window functions.
Example: Course Progress Statusβ
Let's use the CodeFriends dataset to categorize users based on how far they've progressed in a course.
course_progress
| user_id | course_name | progress_percent |
|---|---|---|
| 1 | SQL Basics | 100 |
| 2 | SQL Basics | 85 |
| 3 | SQL Basics | 70 |
| 4 | SQL Basics | 55 |
| 5 | SQL Basics | 30 |
We can use CASE to assign each user a label:
Assigning Course Completion Status
SELECT user_id,
course_name,
progress_percent,
CASE
WHEN progress_percent = 100 THEN 'Completed'
WHEN progress_percent >= 75 THEN 'Almost done'
WHEN progress_percent >= 50 THEN 'Halfway'
ELSE 'Just started'
END AS completion_status
FROM course_progress;
Result:
| user_id | course_name | progress_percent | completion_status |
|---|---|---|---|
| 1 | SQL Basics | 100 | Completed |
| 2 | SQL Basics | 85 | Almost done |
| 3 | SQL Basics | 70 | Halfway |
| 4 | SQL Basics | 55 | Halfway |
| 5 | SQL Basics | 30 | Just started |
When should I use CASE in SQL?β
Use CASE when you need to apply conditional rules directly inside your query.
Itβs ideal for:
- Categorizing or labeling data based on conditions
- Replacing values dynamically
- Embedding simple logic without extra tables or code
This makes CASE especially useful in reporting, dashboards, and analytical queries where flexible data presentation is required.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.