The SQL CASE statement is used to execute conditional logic within SQL queries. It allows you to perform IF-ELSE logic directly in the query, making it useful for conditional expressions, transforming data, or handling different cases based on specific conditions.
Syntax:
SELECT column1,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE default_result
END as alias_name
FROM table_name;
Example:
SELECT employee_name,
CASE
WHEN salary > 50000 THEN ‘High’
WHEN salary BETWEEN 30000 AND 50000 THEN ‘Medium’
ELSE ‘Low’
END as salary_grade
FROM employees;
In this example, the CASE statement categorizes employees based on their salary into “High”, “Medium”, or “Low” salary grades. The CASE statement can be used in SELECT, UPDATE, and ORDER BY clauses.