In SQL Server, you can use the CASE statement to perform IF…THEN logic within a SELECT statement. The CASE statement evaluates a list of conditions and returns one of multiple possible result expressions.
Here’s the basic syntax for using a CASE statement:
SELECT
column1,
column2,
CASE
WHEN condition1 THEN result1
WHEN condition2 THEN result2
...
ELSE default_result
END AS alias_name
FROM
table_name;
condition1,condition2, … are the conditions you want to test.result1,result2, … are the values returned if the corresponding condition is true.default_resultis the value returned if none of the conditions are true. TheELSEpart is optional.alias_nameis the name you want to give to the result of theCASEstatement (this is also optional).
Example
Suppose you have a table named Employees with a column Salary. You want to categorize each employee as ‘Low’, ‘Medium’, or ‘High’ based on their salary:
SELECT
EmployeeID,
Name,
Salary,
CASE
WHEN Salary < 30000 THEN 'Low'
WHEN Salary BETWEEN 30000 AND 60000 THEN 'Medium'
WHEN Salary > 60000 THEN 'High'
ELSE 'Not Specified' -- This line is optional
END AS SalaryCategory
FROM
Employees;
In this example, for each row in the Employees table, the CASE statement checks the Salary column and assigns a SalaryCategory based on the specified conditions.