In this tutorial, we will learn how to use CASE
statement using SQL.
CASE
Statement has the functionality like IF-THEN-ELSE Statement.NULL
.CASE
WHEN CONDITION1 THEN result1
WHEN CONDITION2 THEN result2
WHEN CONDITION(N) THEN resultN
ELSE result
END;
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 |
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:
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,
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;
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 |