100 Days of SQL


Day 59 – SQL CASE Keyword

SQL CASE keyword is used to add conditional logic to a SQL statement, allowing you to perform different actions based on different conditions. The CASE statement can be used in various SQL statements, including SELECT, WHERE, ORDER BY, and GROUP BY.

The syntax for using the CASE keyword is as follows:

SELECT column_name,
        WHEN condition1 THEN result1
        WHEN condition2 THEN result2
        ELSE result3
FROM table_name;

Here, column_name is the name of the column that you want to include in the query result, and condition1, condition2, and result3 are the conditions and corresponding results that you want to apply to the data.

For example, the following SQL statement selects the customer name and their credit status, and assigns a value of “Good” or “Bad” based on their credit limit:

SELECT CustomerName,
        WHEN CreditLimit > 10000 THEN 'Good'
        ELSE 'Bad'
    END AS CreditStatus
FROM Customers;

In this case, the CASE statement is used to add a conditional logic that assigns the value “Good” to customers with a credit limit greater than 10000, and “Bad” to all other customers.

Note that the CASE keyword can be used with multiple conditions and corresponding results by using multiple WHEN clauses. Also, an ELSE clause can be included to specify a default value if none of the conditions are met.

The CASE keyword is a powerful tool for adding conditional logic to SQL queries and is often used in combination with other SQL keywords to perform complex data analysis and transformation.