Saturday, October 14, 2023

SQL Server CASE Statement

The SQL Server `CASE` statement is a powerful and flexible conditional expression used to perform conditional logic within SQL queries. It allows you to execute different code or return different values based on a specified condition. The basic syntax of the `CASE` statement in SQL Server is as follows:

```sql
CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    [ELSE else_result]
END
```

Here's a breakdown of how the `CASE` statement works:

1. `CASE` is the keyword that starts the `CASE` statement.

2. You can have one or more `WHEN` clauses to specify different conditions. When a condition evaluates to true, the corresponding result is returned.

3. `condition1`, `condition2`, etc., are expressions or conditions that are evaluated. When a condition is true, the result for that condition is returned.

4. `result1`, `result2`, etc., are the values or expressions to return when their corresponding conditions are met.

5. You can optionally include an `ELSE` clause to specify a default result if none of the conditions match. If no conditions match and there is no `ELSE` clause, the `CASE` statement returns `NULL`.

Here's an example of using the `CASE` statement in a SQL query to categorize employees based on their salary:

```sql
SELECT
    EmployeeName,
    Salary,
    CASE
        WHEN Salary >= 50000 THEN 'High Salary'
        WHEN Salary >= 30000 THEN 'Medium Salary'
        ELSE 'Low Salary'
    END AS SalaryCategory
FROM
    Employees;
```

In this example, the `CASE` statement categorizes employees into "High Salary," "Medium Salary," or "Low Salary" based on their salary values.

You can also use the `CASE` statement within other SQL clauses, such as `SELECT`, `UPDATE`, and `INSERT`, to conditionally transform or select data. It's a powerful tool for data manipulation and reporting within SQL Server.

No comments:

Post a Comment