SQL IF statement executes different queries based on conditions. The syntax is as follows: IF (condition)statement1ELSEstatement2. Among them, condition is the condition, statement1 is the statement executed when the condition is true, and statement2 is the statement executed when the condition is false. Nested IF statements can handle more complex conditions, and IF statements can be used with other SQL statements.
Usage of IF statement in SQL
SQL IF statement is used to execute different queries based on conditions. The syntax is as follows:
<code class="sql">IF (condition) statement1 ELSE statement2</code>
where:
condition
is the condition to be tested. statement1
is a statement that is executed when the condition is true. statement2
is a statement that is executed when the condition is false. Example:
<code class="sql">SELECT CASE WHEN age >= 18 THEN '成年' ELSE '未成年' END AS age_category FROM users;</code>
In this example, the IF statement is used to determine the age of each user based on the value of the age
column Age category. If age
is greater than or equal to 18, returns "adult"; otherwise, returns "minor".
Nested IF statements:
You can use nested IF statements to handle more complex conditions. For example:
<code class="sql">SELECT CASE WHEN age >= 18 THEN CASE WHEN gender = 'M' THEN '成年男性' ELSE '成年女性' END ELSE '未成年' END AS age_category FROM users;</code>
In this nested IF statement, the age category is first determined based on age
, and then the specific gender category is determined based on gender
.
Note:
The above is the detailed content of Usage of if statement in sql. For more information, please follow other related articles on the PHP Chinese website!