CASE Expression in SQL

🔀 The CASE expression in SQL is used to implement conditional logic within a query. It works similarly to an if-else or switch statement in programming languages, allowing you to return different values based on specified conditions. The CASEexpression is commonly used for categorizing data, creating calculated columns, custom sorting, and conditional aggregation.

📖 What is the CASE Expression?

The CASE expression evaluates one or more conditions in order. As soon as a condition evaluates to TRUE, SQL returns the corresponding result and stops checking the remaining conditions. If none of the conditions match, the optional ELSE clause is returned.

Information

CASE is an expression, not a control-flow statement. It returns a single value and can be used wherever an expression is allowed in an SQL query.

📝 Types of CASE Expressions

SQL supports two forms of the CASE expression:

  • 🔹 Simple CASE Expression
  • 🔹 Searched CASE Expression

1ī¸âƒŖ Simple CASE Expression

A simple CASE compares a single expression against multiple possible values.

Simple CASE Syntax

CASE expression
    WHEN value1 THEN result1
    WHEN value2 THEN result2
    ...
    ELSE default_result
END

Example: Department Names

Simple CASE Example

SELECT
    Name,
    Department,
    CASE Department
        WHEN 'CS' THEN 'Computer Science'
        WHEN 'IT' THEN 'Information Technology'
        WHEN 'ME' THEN 'Mechanical Engineering'
        ELSE 'Other Department'
    END AS DepartmentName
FROM Students;

2ī¸âƒŖ Searched CASE Expression

A searched CASE evaluates one or more Boolean conditions and is the more flexible form of the expression.

Searched CASE Syntax

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

Example: Grade Classification

Grade Classification

SELECT
    Name,
    Marks,
    CASE
        WHEN Marks >= 90 THEN 'A'
        WHEN Marks >= 80 THEN 'B'
        WHEN Marks >= 70 THEN 'C'
        WHEN Marks >= 60 THEN 'D'
        ELSE 'F'
    END AS Grade
FROM Students;

📊 Sample Table

Assume the following Students table:

StudentIDNameDepartmentMarks
101AliceComputer Science92
102BobMathematics85
103CharliePhysics72
104DavidComputer Science58

đŸˇī¸ CASE in the SELECT Statement

One of the most common uses of CASE is creating new calculated columns based on conditions.

Pass or Fail Status

SELECT
    Name,
    Marks,
    CASE
        WHEN Marks >= 50 THEN 'Pass'
        ELSE 'Fail'
    END AS Result
FROM Students;

🔍 CASE in the WHERE Clause

Although less common, CASE can also be used inside the WHERE clause when conditional filtering is required.

CASE in WHERE

SELECT *
FROM Students
WHERE
CASE
    WHEN Department = 'Computer Science'
        THEN Marks >= 90
    ELSE Marks >= 80
END;

📈 CASE in ORDER BY

CASE can customize the sorting order of query results.

Custom Sorting

SELECT Name,
       Department
FROM Students
ORDER BY
CASE
    WHEN Department = 'Computer Science' THEN 1
    WHEN Department = 'Mathematics' THEN 2
    ELSE 3
END;

📊 CASE with Aggregate Functions

Combining CASE with aggregate functions enables conditional calculations and reporting.

Conditional Counting

SELECT
    COUNT(
        CASE
            WHEN Marks >= 90 THEN 1
        END
    ) AS ExcellentStudents
FROM Students;

Conditional SUM

SELECT
    SUM(
        CASE
            WHEN Department = 'Computer Science'
            THEN Marks
            ELSE 0
        END
    ) AS TotalCSMarks
FROM Students;

📌 CASE with UPDATE

The CASE expression can also be used to update values based on conditions.

Update Grades

UPDATE Students
SET Grade =
CASE
    WHEN Marks >= 90 THEN 'A'
    WHEN Marks >= 80 THEN 'B'
    WHEN Marks >= 70 THEN 'C'
    ELSE 'D'
END;

📊 Simple CASE vs Searched CASE

FeatureSimple CASESearched CASE
Comparison TypeCompares one expression with values.Evaluates Boolean conditions.
FlexibilityLimitedHighly flexible
Best Used ForMatching exact values.Ranges and complex logic.
Most CommonNoYes

đŸ’ŧ Real-World Example

A university wants to display the performance level of each student instead of showing only numerical marks.

Student Performance Report

SELECT
    StudentID,
    Name,
    Marks,
    CASE
        WHEN Marks >= 90 THEN 'Excellent'
        WHEN Marks >= 75 THEN 'Good'
        WHEN Marks >= 50 THEN 'Average'
        ELSE 'Needs Improvement'
    END AS Performance
FROM Students
ORDER BY Marks DESC;

This query converts raw marks into meaningful performance categories that are easier to understand in reports.

âš ī¸ Best Practices

Best Practice

Use the searched CASE expression for range-based conditions, always include an ELSE clause to handle unmatched cases, keep conditions simple and readable, and use meaningful aliases for calculated columns created with CASE.

🚀 Key Points to Remember

  • 📌 CASE adds conditional logic to SQL queries.
  • 📌 SQL supports both simple and searched CASE expressions.
  • 📌 Conditions are evaluated from top to bottom.
  • 📌 The first matching condition determines the returned value.
  • 📌 ELSE is optional but recommended.
  • 📌 CASE can be used with SELECT, WHERE, ORDER BY, UPDATE, and aggregate functions.
>>"The CASE expression transforms SQL queries from simple data retrieval into intelligent, rule-based reporting."

Summary

✅ The CASE expression is one of SQL's most powerful features for implementing conditional logic. By mastering both simple and searched CASE expressions, you can categorize data, customize reports, perform conditional calculations, and build more dynamic, readable, and efficient SQL queries.