The SQL CASE statement is a conditional expression that allows you to perform if/then logic within SQL queries. It evaluates conditions in sequence and returns a corresponding result when the first true condition is met. If no conditions are true, it returns the result specified in the optional ELSE clause, or NULL if ELSE is omitted. The CASE statement always ends with END.
Basic Syntax
sql
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE result
END
Explanation
- CASE initiates the conditional logic.
- WHEN specifies a condition to test.
- THEN specifies the result when the condition is true.
- ELSE is optional and handles cases where no conditions match.
- END marks the end of the CASE statement.
Example
sql
SELECT player_name, year,
CASE
WHEN year = 'SR' THEN 'yes'
ELSE 'no'
END AS is_a_senior
FROM players;
This example checks if the year
column equals 'SR'. If true, it returns
'yes'; otherwise, it returns 'no' in the output column is_a_senior
.