How to Use CASE Statements in SQL

How to Use CASE Statements in SQL

CASE statements are perhaps one of the most powerful tools that exist inside SQL. You can integrate conditional logic within your queries by using the "if-then-else" logic inside SQL. Manipulating and analyzing data with complicated code is not required. Below, the guide covers the basics of case statement, syntax, and examples to learn from.

What is CASE Statement SQL?

CASE statement in SQL is a conditional expression, as it evaluates a set of conditions and returns one value for the first true condition. It may also specify a default value by using the ELSE clause if no condition in the CASE statement evaluates to true.

Important Characteristics of CASE Statements:

1. CASE statements both have SELECT and WHERE clause available.

2. Case statements enable the dynamic column creation.

3. Supports multiple comparisons, including equality and ranges.

4. Reduces complex SQL queries with simplistic logic.

Note: The basic syntax of CASE statement has been used here for simplicity while explaining the concept. However, in a typical SQL query, CASE statement can be used along with other conditions and logic to achieve the desired result.

Syntax of CASE Statement

Basic Syntax:

CASE

    WHEN condition1 THEN result1

WHEN condition2 THEN result2

    ELSE default_result

END

ELSE default_result

    END AS alias_name

FROM table_name;

In WHERE Clause:

SELECT column1

FROM table_name

WHERE 

    CASE

        WHEN condition1 THEN true_condition

        ELSE false_condition

    END = some_value;

Examples of Using CASE Statements in SQL

1. Conditional Classification

Let's say you have a table called employees with columns employee_id, salary, and department. You'll classify the employees according to their salary being in one of the following ranges:

SELECT

employee_id,

salary,

CASE

            WHEN salary < 50000 THEN 'Low'

            WHEN salary BETWEEN 50000 AND 100000 THEN 'Medium'

ELSE 'High'

END

Result: A list of employees with salary categories (Low, Medium, High).

2. Calculate Discounts

Sales table product_name and price, calculate discount based on range of price:

SELECT 

    product_name, 

    price,

    CASE

WHEN price < 100 THEN price * 0.90

WHEN price BETWEEN 100 AND 500 THEN price * 0.85

        ELSE price * 0.80

END AS discounted_price

FROM sales;

Result: The query returns each product’s price alongside its discounted price.

3. Conditional Filtering in WHERE Clause

Retrieve information about employees from the employees table who earn more than $60,000 or belong to the "IT" department:

SELECT employee_id, department, salary

FROM employees

WHERE  

    CASE

        WHEN department = 'IT' THEN 1

WHEN salary > 60000 THEN 1

        ELSE 0

4. Row-Generating Column Transformation

Convert numeric month values in the sales table to text representations, for instance "1" to "January":

SELECT

  sale_id,

  CASE month

WHEN 1 THEN 'January'

      WHEN 2 THEN 'February'

      WHEN 3 THEN 'March'

ELSE 'Unknown'

    END AS month_name

FROM sales;

Tips for Using CASE Statements Effectively

1. Keep it simple: Avoid deeply nested CASE statements as they can make the query hard to read and maintain.

2. Use ELSE wisely: Always use an ELSE clause to handle unexpected cases, unless you're sure that all the possibilities are covered.

3. Performance tuning: Inside where clause use simple and indexes conditions.

4. Use along with aggregate function: Use CASE along with SUM, COUNT or AVG for heavy-duty analytical usage.

Common use of CASE statements

1. It can be used to classify any range of numbers or dates.

2. It can be used to assign conditional discounts or fees.

3. Translate codes into more readable and descriptive labels.

4. Dynamically creating calculated columns.

5. Filter data conditionally in an elaborate query.

Conclusion 

Of the more versatile statements available in SQL, one is: this statement will bring your queries to life, it being more dynamic and intuitive. Whether you categorize data, have conditional calculations, or need to filter out some results, mastering the CASE statement will come to your aid in SQL skills and writing more efficient queries.

Play with these examples on your database to see how CASE statements can make some kinds of data analysis tasks less complicated. Happy querying!

More Details for programming knowledge link : 

Summary

Best top 5 Laptops for programming 

Amazon link: https://www.howtotech.in/search/label/Amazon%20Offers?m=1

Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.