Explain the purpose of the MYSQL CASE statement
The CASE
statement in MySQL is a powerful control
structure that allows you to perform conditional logic in SQL queries.
It is similar to the IF-THEN-ELSE
statement in other programming languages. The CASE
statement is often used to create conditional output in the result set
or to perform conditional operations on data during the query process.
Here's the basic syntax of the CASE
statement:
CASEWHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE defaultResult END
condition1
,condition2
, etc.: These are the conditions that are evaluated in the order they appear. If a condition is true, the correspondingresult
is returned.result1
,result2
, etc.: These are the values returned when the corresponding condition is true.defaultResult
: This is the value returned if none of the conditions are true (optional).
Example 1: Simple CASE Statement
Let's say you have a table orders
with a column order_status
. You want to categorize orders based on their status and assign a label. You can use a CASE
statement for this:
SELECT
order_id, order_status, CASEWHEN order_status
='shipped'THEN'Shipped'WHEN order_status
='processing'THEN'Processing'ELSE'Unknown'ENDAS status_label FROM
orders;
In this example, the CASE
statement checks the order_status
column. If it's "shipped", it returns "Shipped". If it's "processing",
it returns "Processing". If it's any other value, it returns "Unknown".
Example 2: Searched CASE Statement
You can also use a searched CASE
statement, where each WHEN
clause contains its own condition:
SELECT
product_id, quantity, CASEWHEN quantity >10THEN'High demand'WHEN
quantity >0THEN'In stock'ELSE'Out of stock'ENDAS stock_status FROM
products;
In this example, the CASE
statement checks the quantity
column. If quantity
is greater than 10, it returns "High demand". If it's greater than 0
but not more than 10, it returns "In stock". If it's 0 or less, it
returns "Out of stock".
The CASE
statement provides a
way to customize the output of your queries based on specified
conditions, making your SQL queries more flexible and expressive.
Comments
Post a Comment