SQL

SQL Case

SQL Case

This page covers SQL Case.

The concept of “case” is very similar to the “if/else” statements in many other programming languages.

The expression evaluates specific conditions. It then outputs an outcome if one of the conditions is met.

Let’s use the table “student_info” from the previous tutorials.

idsubjectNamegradepassedstudentID
1HistoryC11
2PhysicsA12
3HistoryF03
4BiologyA1NULL
5BiologyE15

Case

The “case” expression has several keywords.

It uses case/end to start and end the expression. The conditions are expressed with a when/then statements.

When refers to the actual condition we need to meet. Then specifies what to return if the particular condition is met.

In addition, there is an “else” statement. Else executes if non of the conditions meet the criteria.

The following is an example of the “case” expression.

SELECT studentID, grade,
CASE
	WHEN grade = 'A' THEN 'The student has an excellent grade!'
	WHEN grade = 'B' THEN 'The student has done very well!'
	WHEN grade = 'C' THEN 'The student has done well!'
	WHEN grade = 'D' THEN 'The student has passed.'
	WHEN grade = 'E' THEN 'The student has barely passed.'
	ELSE 'The student has failed'
END
FROM grade;
studentIDgradeNo Column Name
1CThe student has done well!
2AThe student has an excellent grade!
3FThe student has failed
NULLAThe student has an excellent grade!
5EThe student has barely passed.

To rename the new column name, we can add an alias after the “end” statement (e.g. END AS column_name).

The comprehension of the result should be quite straightforward.

When the grade is “A”, then the expression outputs “The student has done well!”. The same logic follows the rest of the conditions.

The last (else) condition executes if non of the other conditions meet the criteria. The 3rd student has an “F”, which is not in the conditions when/then. Therefore, the query produces the “else” statement.

Let’s look at another example.

SELECT studentID, grade,
CASE
	WHEN passed = 1 THEN 'Pass'
	ELSE 'Fail'
END AS 'Status'
FROM grade;
studentIDgradeStatus
1CPass
2APass
3FFail
NULLAPass
5EPass

Next: SQL Procedure