Using CASE Statements for Conditional Logic in SQL Server like IF THEN

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_result is the value returned if none of the conditions are true. The ELSE part is optional.
  • alias_name is the name you want to give to the result of the CASE statement (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.

Related Posts

Troubleshooting Missing SQL Server Statistics

Learn how to diagnose and fix missing SQL Server statistics through a practical troubleshooting guide, including step-by-step solutions and best practices.

Read more

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from The DBA Hub

Subscribe now to keep reading and get access to the full archive.

Continue reading