Certainly! SQL CASE is a conditional statement used in SQL queries to perform different actions based on specified conditions. It allows you to define multiple conditions and their corresponding actions within a single query. The general syntax for the SQL CASE statement is as follows:
CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... ELSE result_n END
Here’s a breakdown of the different parts:
CASE: Begins the CASE statement.
WHEN condition_1 THEN result_1: Checks if
condition_1is true, and if so, returns
WHEN condition_2 THEN result_2: Checks if
condition_2is true, and if so, returns
ELSE result_n: Optional. If none of the conditions are true, returns
END: Ends the CASE statement.
Here’s an example that demonstrates the usage of SQL CASE:
SELECT product_name, unit_price, CASE WHEN unit_price > 50 THEN 'Expensive' WHEN unit_price > 20 THEN 'Moderate' ELSE 'Cheap' END AS price_category FROM products;
In this example, the query selects the
unit_price columns from the
products table. The CASE statement checks the
unit_price for each product and assigns a
price_category based on the conditions specified. If the
unit_price is greater than 50, it will be categorized as ‘Expensive’. If it’s between 20 and 50, it will be categorized as ‘Moderate’. Otherwise, it will be categorized as ‘Cheap’. The result of the CASE statement is aliased as
The SQL CASE statement is a powerful tool for performing conditional operations in SQL queries, allowing you to customize the output based on specific conditions.