SQL CASE Expression: IF-THEN-ELSE Logic in Queries

SQL is a declarative language, but real-world reporting frequently requires conditional if-then-else branching logic (e.g., "If GPA >= 3.8, label as 'High Distinction'; if GPA >= 3.5, label as 'First Class'"). The CASE expression is SQL's universal way to implement conditional logic across SELECT, WHERE, and ORDER BY clauses.


The Searched CASE Expression Syntax

The searched CASE expression evaluates boolean conditions sequentially from top to bottom. It returns the THEN result for the first condition that evaluates to TRUE:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE default_result
END

Hands-on Example: Categorizing Student GPA Grades

SELECT 
    student_id,
    first_name,
    gpa,
    CASE 
        WHEN gpa >= 3.80 THEN 'High Distinction'
        WHEN gpa >= 3.50 THEN 'First Class with Honors'
        WHEN gpa >= 3.00 THEN 'Second Class'
        ELSE 'Needs Improvement'
    END AS academic_standing
FROM students;
student_id first_name gpa academic_standing
2 Pooja 3.92 High Distinction
3 Aman 3.85 High Distinction
1 Rahul 3.75 First Class with Honors
4 Neha 3.68 First Class with Honors

Custom Sorting with CASE in ORDER BY

You can dictate custom, non-alphabetical sorting sequences using CASE:

-- Custom priority sorting: Urgent tasks first, then Normal, then Low
SELECT task_name, priority
FROM project_tasks
ORDER BY 
    CASE priority
        WHEN 'Urgent' THEN 1
        WHEN 'High' THEN 2
        WHEN 'Normal' THEN 3
        ELSE 4
    END;

Congratulations! You have completed Module 4. Now let us advance to Module 5 and learn summary statistics starting with SQL Aggregate Functions!

Share Share on Facebook Share on Twitter Share on LinkedIn Pin on Pinterest Share on Stumbleupon Share on Tumblr Share on Reddit Share on Diggit

You may also like this!