The CASE WHEN statement is used in SQL to evaluate an expression and return a different value based on specified conditions. Its syntax consists of WHEN clause (conditional expression and return expression), ELSE clause (default expression) and END keyword. It can be used in a variety of scenarios, including assigning values, modifying results, and converting data formats.
Usage of CASE WHEN statement in SQL
CASE WHEN statement is a control flow in SQL query Statement that evaluates different expressions based on specified conditions. The syntax is as follows:
<code class="sql">CASE WHEN <condition 1> THEN <expression 1> WHEN <condition 2> THEN <expression 2> ... ELSE <default_expression> END</code>
Usage:
Steps:
Example:
To assign discounts to customers based on their age group, you can use the following SQL query:
<code class="sql">SELECT CASE WHEN age < 18 THEN 0.1 WHEN age >= 18 AND age < 25 THEN 0.15 WHEN age >= 25 AND age < 35 THEN 0.2 ELSE 0.25 END AS discount FROM customers;</code>
In this query Medium:
Use cases:
The CASE WHEN statement can be used in various scenarios, including:
The above is the detailed content of Usage of case when statement in sql. For more information, please follow other related articles on the PHP Chinese website!