SQL Keyword - CASE

CASE Keyword

The CASE keyword is used to check different conditions and, based on those, give an output.

A case is very useful when we want to give an output based on multiple conditions.

Case is equivalent to if...else if...else.

If all conditions become false, then the part will be executed.

Check multiple conditions and returns a value when the specified condition is met.

We can use case statements in select queries, where clauses, order by clauses, etc.

Syntax

SELECT <COLUMNS>,
CASE
    WHEN <CONDITION_1> THEN <OUTPUT_1>
    WHEN <CONDITION_2> THEN <OUTPUT_2>
    WHEN <CONDITION_3> THEN <OUTPUT_2>
    ELSE <OUTPUT_ELSE>
END FROM <TABLE_NAME>

Example 1

SELECT Emp_Id, Emp_Name,Emp_Salary,
CASE
    WHEN Emp_Salary > 50000 THEN 'Salary Greater Than 50K'
    WHEN Emp_Salary > 40000 THEN 'Salary Greater Than 40K'
    WHEN Emp_Salary > 30000 THEN 'Salary Greater Than 30K'
    ELSE 'Salary Less Than 30K' As 'Salary Description'
END From Employee;

Example 2

Select Emp_Id,Emp_Name,Emp_Age,Emp_Salary,
Case When Emp_Gender = 'Male' Then 'M'
When Emp_Gender = 'Female' Then 'F'
Else 'No Gender Selected' End As 'Gender' From Employee

Example 3

Select * From Employee Order By 
Case Emp_Gender When 'Female' Then Emp_Salary End Desc,
Case Emp_Gender When 'Male' Then Emp_Salary End Asc

Summary

The Case command is used to display different outputs based on different conditions.

Next Recommended Reading Case Statement in SQL Server