• Home
  • SQL CASE Expression

    The SQL CASE statement is a conditional expression that allows you to perform conditional logic in SQL queries. It evaluates a set of conditions and returns a value or performs an action based on the condition that evaluates to true. The CASE statement can be used in various scenarios, such as data transformation, result customization, and conditional aggregations. Here's the basic syntax of the CASE statement:


    sql
    CASE
        WHEN condition1 THEN result1
        WHEN condition2 THEN result2
        ...
        ELSE result
    END

    The CASE statement starts with the keyword `CASE` followed by one or more `WHEN` clauses, each specifying a condition and the corresponding result if the condition is true. The conditions are evaluated in order, and the first condition that evaluates to true triggers the associated result. Optionally, you can include an `ELSE` clause to provide a default result when none of the conditions are true.


    Here's an example to demonstrate the usage of the SQL CASE statement:

    sql
    SELECT customer_name, order_date,
        CASE
            WHEN order_total > 1000 THEN 'High'
            WHEN order_total > 500 THEN 'Medium'
            ELSE 'Low'
        END AS order_priority
    FROM orders;

    In this example, the CASE statement is used to determine the order priority based on the order total. If the order total is greater than 1000, it is considered 'High' priority. If it is greater than 500 but less than or equal to 1000, it is 'Medium' priority. Otherwise, it is 'Low' priority. The result of the CASE statement is aliased as `order_priority` in the query result.


    The SQL CASE statement provides a flexible way to apply conditional logic in SQL queries, allowing you to customize query results based on specified conditions.


    About the Author



    Silan Software is one of the India's leading provider of offline & online training for Java, Python, AI (Machine Learning, Deep Learning), Data Science, Software Development & many more emerging Technologies.

    We provide Academic Training || Industrial Training || Corporate Training || Internship || Java || Python || AI using Python || Data Science etc





     PreviousNext