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, CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ELSE result3 END FROM table_name;
column_name is the name of the column that you want to include in the query result, 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, CASE 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.
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.