What is the CASE statement in SQL?

Overview

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.

Syntax

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:

  • If there is an ELSE clause, it returns it.
  • If there is no ELSE clause, it returns NULL.
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
WHEN condition3 THEN result3
WHEN conditionN THEN resultN
ELSE result
END;
Syntax for adding conditions statements

Example

/* 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 GRADE
WHEN '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

Explanation

  • Line 2–7: We create a table Student.
  • Line 10-17: We insert a few values in the table Student.
  • Line 20–29: We execute the SQL CASE statement.

Output

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.

Free Resources