In this topic, we are going to study another quite useful SQL tool – the CASE statement. It is used for conditional logic and branching within queries. It helps us to apply different actions or expressions based on specified conditions. The CASE statement is particularly beneficial for transforming data, creating calculated fields, and controlling query output based on various criteria.
CASE statement syntax
Let us explore the basic syntax of the CASE statement in SQL. The structure looks as follows:
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2 ...
ELSE default_result
END
The above syntax demonstrates how the CASE statement allows you to perform conditional logic and determine different outcomes based on the specified conditions.
- The
CASEkeyword marks the beginning ofCASEstatement; - Each
WHENclause specifies a condition that is checked; - If the condition in a
WHENclause evaluates to true, the correspondingresultis returned; - You can have multiple
WHENclauses to handle different conditions; - The
ELSEclause provides a defaultresultif none of the conditions are met; - The
ENDkeyword marks the end of theCASEstatement.
Let's explore below few examples where CASE statement can be applied.
Simple CASE statement usage
A simple CASE statement compares an expression to a set of values and returns a result when a match is found. It's often used for categorizing or grouping data.
Suppose we have a table named Employees with columns Name and DepartmentID. We want to categorize employees' departments using their DepartmentID values. The goal is to display the department name for each employee, with a fallback to 'Other' for any unrecognized department IDs.
The SQL will be as follows:
SELECT
Name,
CASE DepartmentID
WHEN 1 THEN 'Sales'
WHEN 2 THEN 'Marketing'
WHEN 3 THEN 'Finance'
ELSE 'Other'
END AS Department
FROM Employees;
In this query:
- The
CASE DepartmentIDpart marks the beginning of the Simple CASE statement. It indicates that we want to compare theDepartmentIDcolumn's values; - Each
WHENclause specifies a value to compare theDepartmentIDagainst (e.g., 1, 2, 3) and the corresponding result to return when a match is found ('Sales', 'Marketing', 'Finance'); - The
ELSE 'Other'part specifies the default result to return when no matches are found betweenDepartmentIDand the specified values; - The
END AS Departmentindicates the end of the CASE statement and assigns an alias 'Department' to the result.
When the query is executed:
- If
DepartmentIDis 1, the result for that row will be 'Sales'; - If
DepartmentIDis 2, the result for that row will be 'Marketing'; - If
DepartmentIDis 3, the result for that row will be 'Finance'; - For any other
DepartmentIDvalues, the result will be 'Other'.
Searched CASE statement usage
A searched CASE statement evaluates multiple conditions and returns a result when the first matching condition is found. It's more versatile and allows complex conditions.
Suppose we have a table ExamScores with columns StudentName and Score, and we want to assign letter grades based on scores.
| StudentName | Score |
|---|---|
| Alice | 95 |
| Bob | 78 |
| Carol | 62 |
| David | 85 |
| Emma | 45 |
Our query will be as follows:
SELECT
StudentName,
Score,
CASE
WHEN Score >= 90 THEN 'A'
WHEN Score >= 80 THEN 'B'
WHEN Score >= 70 THEN 'C'
WHEN Score >= 60 THEN 'D'
ELSE 'F'
END AS Grade
FROM
ExamScores;
The query calculates the letter grade for each student based on their scores. The output will look like this:
| StudentName | Score | Grade |
|---|---|---|
| Alice | 95 | A |
| Bob | 78 | C |
| Carol | 62 | D |
| David | 85 | B |
| Emma | 45 | F |
We can not only categorize our table data but also can perform more elaborate calculations for the new field with the help of CASE statement. You can find more applications by exploring the link.
Benefits of CASE statement
Based on the examples we studied, we can conclude that CASE statement can significantly benefit our work with SQL. The main advantages provided are as follows:
- Conditional Transformations:
CASEstatements allow us to transform data based on specific conditions, making our query results more meaningful and insightful. - Custom Calculations: We can use
CASEto perform custom calculations or derive new fields based on existing data. - Dynamic Control:
CASEprovides dynamic control over query output, allowing us to tailor results based on different scenarios. - Readability: Properly structured
CASEstatements improve query readability.
Conclusion
In the topic above we learned a CASE statement – a versatile and essential tool in SQL, offering a way to perform conditional logic, data transformation, and custom calculations within our queries. By understanding the CASE statement logic effectively, we can enhance our SQL querying skills and create more informative and tailored database reports and outputs. So let's start practicing right away!