Previous

Mysql - CASE Function

The `CASE` function in MySQL is used to implement conditional logic in SQL queries. It allows you to execute a series of conditions and return a specific result when a condition is met. This can be particularly useful for transforming data in your SELECT queries based on certain criteria.

The `CASE` function has two formats:

  • Simple CASE Function

    CASE expression

    WHEN value1 THEN result1

    WHEN value2 THEN result2

    ...

    ELSE default_result

    END

  • Searched CASE Function

    CASE

    WHEN condition1 THEN result1

    WHEN condition2 THEN result2

    ...

    ELSE default_result

    END

Let's consider an `employees` table:

idnamedepartmentsalary
1Jane SmithIT500000
2John DoeHR350000
3Johny SmithIT50000
4Jeffer JoeFinance380000
Example of the Simple CASE Function

To categorize employees by department,

SELECT name, department,

CASE department

WHEN 'IT' THEN 'Technical Department'

WHEN 'HR' THEN 'Human Resources'

WHEN 'Finance' THEN 'Financial Department'

ELSE 'Other Department'

END AS department_category

FROM employees;

In this query,

  • Checks the value of the `department` column.
  • Returns a specific string based on the department's value.
  • Provides a default value with `ELSE` if none of the `WHEN` conditions match.

Output of the following -

namedepartmentdepartment_category
Jane SmithITTechnical Department
John DoeHRHuman Resources
Johny SmithITTechnical Department
Jeffer JoeFinanceFinancial Department
Example of the Searched CASE Function

To categorize employees based on salary ranges, you could use a searched CASE function:

SELECT name, department, salary,

CASE

WHEN salary >= 75000 THEN 'High'

WHEN salary BETWEEN 50000 AND 74999 THEN 'Medium'

ELSE 'Low'

END AS salary_category

FROM employees;

In this query,

  • Evaluates multiple conditions.
  • Returns a result based on which condition is true.
  • The `ELSE` clause provides a default result if none of the conditions are met.

Output of the following -

namedepartmentsalarysalary_category
Jane SmithIT500000High
John DoeHR350000High
Johny SmithIT50000Medium
Jeffer JoeFinance380000High
Benefits of Using the `CASE` Function
  • Flexibility: Allows you to handle complex conditional logic directly within your SQL queries.
  • Readability: Makes your SQL code easier to understand by clearly defining different cases and their corresponding results.
  • Efficiency: Reduces the need for multiple separate queries or complex application logic to handle conditional data transformations.
  Previous

Aspirant's Home is an innovative educational and career development platform designed to empower individuals in achieving their academic and professional aspirations.
Terms of Use   About Us   Privacy Policy