Case in SQL
? CASE Statement in SQL
The CASE statement is used to create conditional logic inside SQL queries. It works like an IF-THEN-ELSE or switch statement in programming.
? Syntax
1. Simple CASE
CASE expression WHEN value1 THEN result1 WHEN value2 THEN result2 ... ELSE result_defaultENDCompares an expression to values and returns the matching result.
2. Searched CASE
CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE result_defaultENDEvaluates multiple conditions in order and returns the result for the first true condition.
? Examples
1. Simple CASE Example: Grade conversion
SELECT student_name, CASE grade WHEN 'A' THEN 'Excellent' WHEN 'B' THEN 'Good' WHEN 'C' THEN 'Average' ELSE 'Poor' END AS performanceFROM students;2. Searched CASE Example: Salary bracket
SELECT employee_name, salary, CASE WHEN salary >= 100000 THEN 'High' WHEN salary >= 50000 THEN 'Medium' ELSE 'Low' END AS salary_levelFROM employees;3. Using CASE in ORDER BY
SELECT * FROM productsORDER BY CASE category WHEN 'Electronics' THEN 1 WHEN 'Furniture' THEN 2 ELSE 3 END;? Key Points
CASEmust end withEND.ELSEis optional; if omitted and no conditions match, returnsNULL.Can be used in
SELECT,WHERE,ORDER BY, etc.Useful for transforming or grouping data dynamically.
Want examples with nested CASE statements or combining CASE with aggregates?