In SQL, the CASE
statement is used to iterate over multiple conditions and return a value when a particular condition is true. It's SQL's way to handle the if-then-else logic.
Every CASE
statement is followed by a series of WHEN...THEN
statements, and it must end with the END
statement.
If none of the conditions are true, the following can occur:
ELSE
clause, it returns it.ELSE
clause, it returns NULL
.CASEWHEN condition1 THEN result1WHEN condition2 THEN result2WHEN condition3 THEN result3WHEN conditionN THEN resultNELSE resultEND;
/* Create table Student */CREATE TABLE Student(ID INT NOT NULL,NAME VARCHAR (20) NOT NULL,GRADE VARCHAR (20) NOT NULL,PRIMARY KEY (ID));/* Insert values in table Student */INSERT INTO Student (ID, NAME, GRADE)VALUES (1, 'Shubham', 'C');INSERT INTO Student (ID, NAME, GRADE)VALUES (2, 'Parth', 'A');INSERT INTO Student (ID, NAME, GRADE)VALUES (3, 'Pratik', 'B');/* Usage of CASE statement */SELECT *,CASE GRADEWHEN 'A' THEN 'Excellent'WHEN 'B' THEN 'Good'WHEN 'C' THEN 'Average'WHEN 'D' THEN 'Poor'WHEN 'F' THEN 'Fail'ELSE 'N/A'END 'REMARK'FROM Student
Student
.Student
.CASE
statement.In the output, we can see a column, REMARK
, that has been added and was created using the SQL CASE
statement. It uses the GRADE
value to iterate over the WHEN...THEN
statements to find the appropriate remark.