The `CASE` expression in MySQL is used for conditional logic in SQL queries, allowing you to return specific values based on different conditions. It functions similarly to an if-else statement in programming languages.
Usage
The `CASE` expression is utilized to execute conditional logic within SQL queries, primarily in `SELECT`, `UPDATE`, and `ORDER BY` clauses. It evaluates conditions in order and returns a specified value when the first true condition is encountered.
CASEWHEN condition1 THEN result1
WHEN condition2 THEN result2
...ELSE resultN
END;Altyapı:
In this syntax, `CASE` checks each condition sequentially and returns the corresponding result for the first true condition; if none are true, it returns the `ELSE` result.
Examples
1. Basic Case Usage
SELECT product_name,CASEWHEN stock_quantity >0THEN'In Stock'ELSE'Out of Stock'ENDAS stock_status
FROM products;Altyapı:
This example evaluates the `stock_quantity` and returns 'In Stock' if the quantity is greater than zero, otherwise 'Out of Stock'.
The `CASE` expression in MySQL is used for conditional logic in SQL queries, allowing you to return specific values based on different conditions. It functions similarly to an if-else statement in programming languages.
Usage
The `CASE` expression is utilized to execute conditional logic within SQL queries, primarily in `SELECT`, `UPDATE`, and `ORDER BY` clauses. It evaluates conditions in order and returns a specified value when the first true condition is encountered.
In this syntax, `CASE` checks each condition sequentially and returns the corresponding result for the first true condition; if none are true, it returns the `ELSE` result.
Examples
1. Basic Case Usage
This example evaluates the `stock_quantity` and returns 'In Stock' if the quantity is greater than zero, otherwise 'Out of Stock'.
2. Multiple Conditions
In this query, the `CASE` expression categorizes employees into salary bands, offering more granular control over output labels.
3. Using CASE in ORDER BY
Here, the `CASE` expression is used to order results based on `order_status`, prioritizing 'Pending', followed by 'Shipped', then any other status.
4. Using CASE in UPDATE
This example shows how `CASE` can be used in an `UPDATE` statement to set the `salary_category` field based on different salary ranges.
Tips and Best Practices