T-SQL Tutorial

Nested case statements in SQL Server


Nested case statements in SQL Server allow you to evaluate multiple conditions and return different results based on the outcome of those conditions. They provide a way to build complex conditional logic within a SQL query.

A nested case statement is constructed by embedding one or more case statements inside another case statement. Each case statement consists of the CASE keyword followed by one or more WHEN clauses and an optional ELSE clause.


Syntax

The syntax for a simple case statement is as follows:

CASE expression
WHEN value1 THEN result1
WHEN value2 THEN result2
...
ELSE else_result
END


Example

Now, let's explore an example of a nested case statement to illustrate its usage. Suppose we have a table called Employees with columns EmployeeID, FirstName, LastName, Salary, and DepartmentID. We want to categorize the employees based on their salary range and department. Here's how we can achieve this using nested case statements:


SELECT
EmployeeID,
FirstName,
LastName,
Salary,
DepartmentID,
CASE
WHEN Salary < 2000 THEN
CASE
WHEN DepartmentID = 1 THEN 'Low Salary - Department 1'
WHEN DepartmentID = 2 THEN 'Low Salary - Department 2'
ELSE 'Low Salary - Other Departments'
END
WHEN Salary >= 2000 AND Salary < 5000 THEN
CASE
WHEN DepartmentID = 1 THEN 'Medium Salary - Department 1'
WHEN DepartmentID = 2 THEN 'Medium Salary - Department 2'
ELSE 'Medium Salary - Other Departments'
END
ELSE
CASE
WHEN DepartmentID = 1 THEN 'High Salary - Department 1'
WHEN DepartmentID = 2 THEN 'High Salary - Department 2'
ELSE 'High Salary - Other Departments'
END
END AS SalaryCategory
FROM
Employees;

In this example, we first check the salary using the outer case statement. If the salary is less than 2000, we further evaluate the department using the inner case statement to determine the appropriate category. Similarly, we handle medium and high salary ranges with their respective department conditions.

The result of the above query will include the EmployeeID, FirstName, LastName, Salary, DepartmentID, and a new column SalaryCategory, which contains the categorized salary information based on the nested case statements.

Nested case statements provide a powerful way to handle complex conditional logic in SQL queries. However, it's important to use them judiciously and keep the code readable and maintainable. In some cases, it might be more appropriate to use other constructs like derived tables, Common Table Expressions (CTEs), or user-defined functions to achieve the desired results.