;

SQL CASE


In this tutorial, we will learn how to use  CASE statement using SQL.

SQL CASE Statement

  • SQL CASE Statement has the functionality like IF-THEN-ELSE Statement.
    If the condition is true, will return the result and if no condition is true, it returns the value in the ELSE clause.
  • If there is no ELSE part and no conditions are true, then it returns NULL.
Syntax - CASE Statement
CASE
    WHEN CONDITION1   THEN result1
    WHEN CONDITION2   THEN result2
    WHEN CONDITION(N) THEN resultN
    ELSE result
END;

Example:

Let us consider this table "Employee" for records.

Table Name: Employee

ID EmpName City Country Gender Salary
1 Shankar Delhi India male 25000
2 Sourabh Delhi India male 30000
3 Ranvijay Mumbai India male 15000
4 Kapil Noida India male 25000
5 Shalini Jaipur India female 18000
6 Rakesh Faridabad India male 23000
7 Akshay Mumbai India male 21000
8 Sarah New York US female 76000
9 Rocky Noida India male 28000

Example of CASE Statement

For adding "Mr." and "Mrs." as a prefix in front of employee name according to their gender using CASE Statement, and this the most asking interview question of SQL, a query will be:

Example
SELECT Id,
(CASE Gender
WHEN 'male' THEN 'Mr.'+EmpName
WHEN 'female' THEN 'Mrs.'+EmpName
ELSE EmpName
END) AS EmpName,City,Country,Gender,Salary
FROM Employee;

OR You can write this statement like this also,

Example
SELECT Id,
(CASE 
WHEN Gender='male' THEN 'Mr.'+EmpName
WHEN Gender='female' THEN 'Mrs.'+EmpName
ELSE EmpName
END) AS EmpName,City,Country,Gender,Salary
FROM Employee;
Output
ID EmpName City Country Gender Salary
1 Mr. Shankar Delhi India male 25000
2 Mr. Sourabh Delhi India male 30000
3 Mr. Ranvijay Mumbai India male 15000
4 Mr. Kapil Noida India male 25000
5 Mrs. Shalini Jaipur India female 18000
6 Mr. Rakesh Faridabad India male 23000
7 Mr. Akshay Mumbai India male 21000
8 Mrs. Sarah New York US female 76000
9 Mr. Rocky Noida India male 28000