The CASE WHEN statement is used to return different values based on conditions. Its usage steps are: Specify conditions: Determine the conditions to be evaluated. Specifies the result: the value returned if the condition is true. Specify an ELSE clause: If no condition is true, a default value is returned (optional).
Usage of CASE WHEN statement in SQL
The CASE WHEN statement is a conditional statement in SQL query language An expression that returns a different value based on specified conditions. The syntax is as follows:
<code class="sql">CASE WHEN condition1 THEN result1 WHEN condition2 THEN result2 ... ELSE default_result END</code>
Usage steps:
Example:
<code class="sql">SELECT CASE WHEN age > 18 THEN '成年' WHEN age >= 13 AND age <= 18 THEN '青少年' ELSE '儿童' END AS age_category FROM students;</code>
Result:
Student ID | Name | Age | Age Category |
---|---|---|---|
John | 20 | Adult | |
Mary | 16 | teenager | |
Peter | 10 | Children |
Other uses:
Advantages:
The above is the detailed content of Usage of casewhen in sql. For more information, please follow other related articles on the PHP Chinese website!