SQL Case statement is like IF THEN ELSE statement. It can be used in a SQL query statement.
And case statements can be classified to 2 types:
Simple Case Expression
Search Case Expression
Simple Case Expression
Description
In simple case expression, contrast an expression with static qualities.
Search Case Expression
Description
In search case expressions, where an expression can be contrasted to multiple conditions consistently.
Conceptual
figure
Syntax
The syntax for case statement is as follows:
CASE expression
WHEN value1 then result1
WHEN value2 then result2
.
.
.
ELSE result
END
If value of expression is equal to value_1 then it will show result_set_1 and like that it will check for all the values mentioned. If it is not matched with no values then it will set the default value mentioned in ELSE part.
Examples
[c]
SELECT order_id,
CASE supplier_id
WHEN 'S1001' THEN 'DELL'
WHEN 'S1002' THEN 'LENOVO'
ELSE 'NO_ITEM' END FROM orders;[/c]
Case statement can be used as following:
[c]SELECT student_id CASE WHEN marks BETWEEN 70 AND 80 THEN 'General Incentive' WHEN marks > 80 Then 'Highest Incentive' ELSE 'No Incentive' END FROM student_details;[/c]
Summary
Key Points
SQL CASE Statement - Similar to IF THEN ELSE statement.