SQL CASE Statement

The SQL CASE statement is similar to the IF-THEN-ELSE statement, where the CASE statement goes through different conditions and returns a value when the first condition is met. So when the condition returns true, it will stop execution and return the result. If all conditions are false, it will execute the ELSE clause and return the value. If there is no ELSE clause then it will return NULL.

CASE statement Syntax :

The syntax of the CASE statement is −

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    WHEN conditionN THEN resultN
    ELSE result
END;
   



CASE statement Example :

Consider the Customer table with the following records -

CustomerID CustomerName Age Address CustomerSalary Gender
1 Aarav 28 Udaipur 28000 M
2 Aarushi 25 Mumbai 30000 F
3 Reyansh 28 Chennai 35000 M
4 Aditi 24 Udaipur 50000 F
5 Sai 30 Mumbai 27000 M


TEST CASE 1 :- The following code is an example, which would fetch the all records from Customer table and change the Gender :-
where M change to Male
and F change to Female

SELECT *
CASE Gender
 WHEN'M' THEN 'Male'
 WHEN'F' THEN 'Female'
END
FROM Customer
   


The result for the respective sql query is as follows −

CustomerID CustomerName Age Address CustomerSalary Gender
1 Aarav 28 Udaipur 28000 Male
2 Aarushi 25 Mumbai 30000 Female
3 Reyansh 28 Chennai 35000 Male
4 Aditi 24 Udaipur 50000 Female
5 Sai 30 Mumbai 27000 Male





Visit :


Discussion


* You must be logged in to add comment.