SQL CASE statement: logica toepassen op een selectie [TUTORIAL]
Learning

SQL CASE statement: logica toepassen op een selectie [TUTORIAL]

2046 × 1224px June 21, 2025 Ashley
Download

SQL is a knock-down lyric used for managing and manipulate relational database. One of its most versatile features is the CASE WHEN argument, which let for conditional logic within inquiry. This lineament is particularly utile when you need to perform different activity base on different conditions. In this post, we will delve into the intricacies of the CASE WHEN statement in SQL, exploring its syntax, use cases, and good exercise.

Understanding the CASE WHEN Statement

The LAWSUIT WHEN statement in SQL is used to return different values free-base on different weather. It is like to the if-else statements in programme languages. The basic syntax of the EVENT WHEN argument is as follows:

CASE
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
    ...
    ELSE resultN
END

Here, condition1, condition2, etc., are the conditions that you need to check. If a stipulation is true, the corresponding consequence is returned. If none of the conditions are true, the result specify in the ELSE clause is returned. The ELSE clause is optional.

Basic Syntax and Examples

Let's start with a elementary illustration to instance the basic syntax of the CASE WHEN argument. Suppose we have a table named employee with the following construction:

EmployeeID Gens Department Salary
1 John Doe HR 50000
2 Jane Smith IT 60000
3 Alice Johnson Finance 70000

We want to categorize the employees based on their remuneration. Employees earning less than 50,000 should be categorized as 'Low ', those earning between 50,000 and 70,000 as 'Medium ', and those garner more than 70,000 as 'High '. We can use the CASE WHEN argument as follows:

SELECT
    EmployeeID,
    Name,
    Department,
    Salary,
    CASE
        WHEN Salary < 50000 THEN 'Low'
        WHEN Salary BETWEEN 50000 AND 70000 THEN 'Medium'
        ELSE 'High'
    END AS SalaryCategory
FROM
    employees;

This query will return the following result:

EmployeeID Gens Department Salary SalaryCategory
1 John Doe HR 50000 Medium
2 Jane Smith IT 60000 Medium
3 Alice Johnson Finance 70000 High

In this illustration, the CASE WHEN statement is expend to make a new column SalaryCategory establish on the value of the Salary column.

Using CASE WHEN in WHERE Clause

The CASE WHEN argument can also be used in the WHERE article to filter platter based on multiple weather. for illustration, hypothecate we desire to retrieve employees who are either in the 'HR' section or have a salary great than 60,000. We can use the CASE WHEN statement as follow:

SELECT
    EmployeeID,
    Name,
    Department,
    Salary
FROM
    employees
WHERE
    CASE
        WHEN Department = 'HR' THEN 1
        WHEN Salary > 60000 THEN 1
        ELSE 0
    END = 1;

This question will render the next result:

EmployeeID Gens Department Salary
1 John Doe HR 50000
2 Jane Smith IT 60000
3 Alice Johnson Finance 70000

In this representative, the CASE WHEN argument is used to filter platter establish on multiple weather in the WHERE clause.

Nested CASE WHEN Statements

Sometimes, you may ask to use nested CASE WHEN argument to cover more complex conditional logic. Nested CASE WHEN statements grant you to evaluate multiple weather within a individual query. for instance, suppose we need to categorise employee based on their department and salary. We can use nested CASE WHEN statement as follows:

SELECT
    EmployeeID,
    Name,
    Department,
    Salary,
    CASE
        WHEN Department = 'HR' THEN
            CASE
                WHEN Salary < 50000 THEN 'Low'
                WHEN Salary BETWEEN 50000 AND 70000 THEN 'Medium'
                ELSE 'High'
            END
        WHEN Department = 'IT' THEN
            CASE
                WHEN Salary < 60000 THEN 'Low'
                WHEN Salary BETWEEN 60000 AND 80000 THEN 'Medium'
                ELSE 'High'
            END
        ELSE 'Other'
    END AS SalaryCategory
FROM
    employees;

This query will return the following result:

EmployeeID Gens Department Salary SalaryCategory
1 John Doe HR 50000 Medium
2 Jane Smith IT 60000 Medium
3 Alice Johnson Finance 70000 Other

In this example, the nested CASE WHEN statements are expend to categorise employees establish on their section and pay.

💡 Billet: Nested SUIT WHEN statements can become complex and unmanageable to read. It is significant to use them judiciously and to check that the logic is open and easygoing to understand.

Using CASE WHEN with Aggregate Functions

The CASE WHEN argument can also be used with aggregated mapping to perform conditional aggregation. for instance, suppose we need to cipher the mean salary of employee in different departments. We can use the CASE WHEN statement with the AVG purpose as postdate:

SELECT
    Department,
    AVG(CASE
        WHEN Department = 'HR' THEN Salary
        ELSE NULL
    END) AS AvgHRSalary,
    AVG(CASE
        WHEN Department = 'IT' THEN Salary
        ELSE NULL
    END) AS AvgITSalary,
    AVG(CASE
        WHEN Department = 'Finance' THEN Salary
        ELSE NULL
    END) AS AvgFinanceSalary
FROM
    employees;

This query will regress the next termination:

Department AvgHRSalary AvgITSalary AvgFinanceSalary
HR 50000 CYPHER NAUGHT
IT ZIP 60000 NAUGHT
Finance NULL NIX 70000

In this example, the CASE WHEN argument is employ with the AVG part to compute the mean salary of employee in different departments.

Best Practices for Using CASE WHEN in SQL

While the CAUSA WHEN argument is a powerful tool, it is crucial to use it effectively to insure that your enquiry are efficient and easy to interpret. Here are some best praxis for apply INSTANCE WHEN in SQL:

  • Continue it Simple: Avoid utilize excessively complex CASE WHEN statements. If your logic becomes too rarify, reckon interrupt it down into smaller, more manageable component.
  • Use Meaningful Alias: When creating new columns with CASE WHEN, use meaningful aliases to get your outcome easier to interpret.
  • Optimize Execution: Be mindful of the performance entailment of employ CASE WHEN statements, especially in turgid datasets. Ensure that your queries are optimized for execution.
  • Test Thoroughly: Always test your CASE WHEN statement soundly to ensure that they render the expected results. Pay peculiar attention to edge cases and unexpected conditions.

By following these best practices, you can insure that your EXAMPLE WHEN argument are efficacious, effective, and leisurely to read.

to summarize, the LAWSUIT WHEN argument in SQL is a versatile and powerful tool for adding conditional logic to your queries. Whether you are categorizing data, filtering disc, or performing conditional accumulation, the CAUSE WHEN statement provides a elastic way to manage complex conditional logic. By understanding its syntax, use cases, and better practices, you can leverage the entire potentiality of the SUIT WHEN argument to heighten your SQL queries and amend your data management capacity.

Related Terms:

  • multiple case when in sql
  • if in sql
  • nested lawsuit when in sql
  • between in sql
  • causa when in sql select
  • instance when in sql oracle