SQL Case
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:
sql
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 ifcondition_1
is true, and if so, returnsresult_1
.WHEN condition_2 THEN result_2
: Checks ifcondition_2
is true, and if so, returnsresult_2
.ELSE result_n
: Optional. If none of the conditions are true, returnsresult_n
.END
: Ends the CASE statement.
Here’s an example that demonstrates the usage of SQL CASE:
sql
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 product_name
and 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 price_category
.
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.