Case when statement in SQL

The CASE WHEN statement in SQL is used for conditional logic within a query, similar to an "if-else" statement in programming. It allows us to return different values based on specific conditions.

SQL Syntax

SELECT column_name,
       CASE 
           WHEN condition1 THEN result1
           WHEN condition2 THEN result2
           ELSE result3
       END AS alias_name
FROM table_name; 

Example: Suppose we have a table called Employees with a column Salary.

Table: Employees

EmployeeIDEmployeeNameSalary
1John80000
2Alice50000
3Bob30000
4Carol75000
5Dave45000

Task: We want to categorize the employees based on their salary into three groups:

SQL

SELECT EmployeeID, 
       EmployeeName, 
       Salary,
       CASE 
           WHEN Salary > 70000 THEN 'High'
           WHEN Salary BETWEEN 40000 AND 70000 THEN 'Medium'
           ELSE 'Low'
       END AS SalaryCategory
FROM Employees; 

The result of the above query is shown below:

EmployeeIDEmployeeNameSalarySalaryCategory
1John80000High
2Alice50000Medium
3Bob30000Low
4Carol75000High
5Dave45000Medium

Explanation:

We can apply more complex conditions inside the CASE WHEN block based on our specific use case.