- SQL Basics
- SQL Introduction
- SQL Syntax
- SQL Sample Database
- SQL SELECT
- SQL WHERE
- SQL ORDER BY
- SQL DISTINCT
- SQL LIMIT
- SQL FETCH
- SQL AND
- SQL OR
- SQL BETWEEN
- SQL IN
- SQL LIKE
- SQL IS NULL
- SQL Comparison Operators
- SQL Logical Operators
- SQL Alias
- SQL CASE
- Joins and Subqueries
- SQL INNER JOIN
- SQL LEFT JOIN
- SQL RIGHT JOIN
- SQL FULL OUTER JOIN
- SQL SELF JOIN
- SQL CROSS JOIN
- SQL Subquery
- SQL Correlated Subquery
- SQL UNION
- SQL INTERSECT
- SQL EXCEPT
- Aggregate Functions
- SQL AVG
- SQL COUNT
- SQL MAX
- SQL MIN
- SQL SUM
- SQL GROUP BY
- SQL HAVING
- SQL ROLLUP
- SQL CUBE
- SQL GROUPING SETS
- Database Management
- SQL CREATE DATABASE
- SQL ALTER DATABASE
- SQL DROP DATABASE
- SQL BACKUP DATABASE
- SQL SHOW DATABASES
- SQL SELECT DATABASE
- Table Management
- SQL CREATE TABLE
- SQL ALTER TABLE
- SQL ADD COLUMN
- SQL DROP COLUMN
- SQL DROP TABLE
- SQL TRUNCATE TABLE
- SQL SHOW TABLES
- SQL RENAME TABLE
- SQL Constraints
- SQL Primary Key
- SQL Foreign Key
- SQL UNIQUE Constraint
- SQL CHECK Constraint
- SQL NOT NULL Constraint
SQL CASE
The SQL CASE statement is your primary tool for implementing conditional logic within a query. If you have experience with programming languages like Python, Java, or JavaScript, you can think of CASE as the SQL equivalent of an if-else or switch statement. It allows you to evaluate conditions and return specific values based on the result, making your data much more readable and meaningful for end-users.
While most commonly used in SELECT statements to transform raw data into categories, it is also incredibly powerful when used in UPDATE, DELETE, and ORDER BY clauses to handle complex business rules directly in the database layer.
Types of CASE Statements
- Simple CASE: Best for equality checks against a single expression.
- Searched CASE: Best for complex logic, ranges, and multiple conditions.
1. Simple CASE
The Simple CASE statement compares a specific expression or column against a list of values. It is highly efficient when you are looking for an exact match (equality) and want to map those values to a more descriptive output.
Syntax:
SELECT column_name,
CASE column_name
WHEN value1 THEN result1
WHEN value2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
ELSE clause. If no conditions are met and there is no ELSE, the CASE statement will return NULL, which might break your application logic if you expect a string or number.
Example:
SELECT first_name,
CASE department_id
WHEN 1 THEN 'Sales'
WHEN 2 THEN 'Marketing'
WHEN 3 THEN 'Engineering'
ELSE 'Unassigned'
END AS department_name
FROM employees;
- In this example, the database looks at the
department_id. If it matches 1, it outputs 'Sales'. If it matches 2, it outputs 'Marketing'. If it doesn't match any of theWHENclauses, it defaults to 'Unassigned'.
2. Searched CASE
The Searched CASE statement is far more flexible. Instead of comparing a single column to a value, it evaluates boolean expressions. This allows you to use operators like >, <, AND, OR, and LIKE.
Syntax:
SELECT column_name,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
ELSE result3
END AS alias_name
FROM table_name;
CASE statement stops evaluating as soon as it finds the first true condition. Always place your most specific conditions at the top and your more general conditions toward the bottom.
Example:
SELECT first_name, salary,
CASE
WHEN salary >= 10000 THEN 'Executive'
WHEN salary >= 5000 THEN 'Senior'
WHEN salary >= 3000 THEN 'Mid-Level'
ELSE 'Junior'
END AS career_tier
FROM employees;
- In this example, we categorize employees based on their salary range. An employee earning 12,000 matches the first condition and is labeled 'Executive'. If we had put the 'Mid-Level' check (>= 3000) first, that 12,000 earner would have incorrectly been labeled 'Mid-Level' because 12,000 is indeed greater than 3,000.
CASE in ORDER BY
One of the most powerful real-world uses of CASE is custom sorting. Sometimes, alphabetical or numerical sorting isn't enough; you may need to prioritize specific data points at the top of your list.
Example:
SELECT task_name, priority_level
FROM tasks
ORDER BY
CASE
WHEN priority_level = 'Urgent' THEN 1
WHEN priority_level = 'High' THEN 2
WHEN priority_level = 'Medium' THEN 3
ELSE 4
END;
- In this query, instead of sorting alphabetically (which would put 'High' before 'Urgent'), we assign numeric weights. 'Urgent' tasks are assigned 1, ensuring they appear at the very top of the result set.
CASE with Aggregates
Using CASE inside aggregate functions like SUM() or COUNT() is a pro-level technique used to create "pivot" reports. This allows you to count or sum data for specific conditions within a single row.
Example:
SELECT department_id,
COUNT(CASE WHEN salary >= 5000 THEN 1 END) AS high_earners,
COUNT(CASE WHEN salary < 5000 THEN 1 END) AS standard_earners
FROM employees
GROUP BY department_id;
- Instead of running two separate queries, this single query provides a breakdown of high vs. low earners per department by conditionally counting records.
Key Points
- Simple CASE: Uses a single expression and checks for strict equality.
- Searched CASE: Uses boolean conditions, allowing for ranges and complex logic.
- Aliases: Always use
END ASto give your calculated column a readable name. - Order of Evaluation: SQL evaluates
WHENclauses sequentially and exits after the first match. - Data Types: All results in the
THENandELSEclauses must be of the same or compatible data types.
Summary
The SQL CASE statement is a fundamental tool for any developer working with data. By moving logic from your application code into your SQL queries, you can produce cleaner, more efficient, and more descriptive reports. Whether you are renaming status codes, bucketizing age ranges, or creating custom sorting logic, CASE provides the flexibility needed to handle diverse business requirements directly within your database.