The CASE expression adds conditional logic to SQL queries — similar to an if/else. Use it to return different values from a single SELECT (or in UPDATE/ORDER BY/aggregations) depending on evaluated conditions.
CASE evaluates conditions and returns a value for the row.WHEN wins.ELSE to provide a default result (avoids NULL).SELECT, UPDATE, ORDER BY, and inside aggregates.
-- General CASE expression syntax: checks conditions and returns corresponding results
SELECT column1, column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
-- Example: group employees into department teams using CASE
SELECT employee_id, first_name, last_name,
CASE
WHEN department = 'Sales' THEN 'Sales Team'
WHEN department = 'IT' THEN 'Tech Team'
ELSE 'Other Team'
END AS department_group
FROM employees;
For each row in employees the CASE expression evaluates the department value:
department = 'Sales' → department_group = Sales Teamdepartment = 'IT' → department_group = Tech Teamdepartment_group = Other Team (from ELSE)This allows a single SELECT to add human-friendly or computed categories without changing source data.
ELSE when appropriate to avoid unexpected NULL results.CASE can become hard to read — consider helper columns or views for clarity.CASE in ORDER BY to implement custom sorting (e.g., prioritise statuses).SUM(CASE WHEN ... THEN 1 ELSE 0 END) or similar for conditional counts.CASE within an UPDATE to set a status column based on numeric ranges (e.g., score >= 90 → 'A').ORDER BY CASE.SUM(CASE ...).