IF statement is used for conditional execution in SQL. Its syntax is: IF condition THEN true_statement [ELSE false_statement] END IF; usage includes: selecting and executing different SQL statement blocks based on conditions, such as dynamically displaying messages based on age. , update records, delete records or set variables.
Usage of IF in SQL
IF statement is used for conditional execution in SQL, allowing execution based on specified conditions Execute different blocks of SQL statements. Its basic syntax is as follows:
<code class="sql">IF (condition) THEN true_statement [ELSE] false_statement END IF;</code>
Usage instructions:
Example:
Suppose we have a table namedcustomers which contains the following data:
name | age | |
---|---|---|
John Doe | 30 | |
Jane Smith | 25 | ##3 |
18 |
<code class="sql">SELECT id, name, CASE WHEN age > 25 THEN 'Eligible for VIP discount' ELSE 'Not eligible for VIP discount' END AS eligibility FROM customers;</code>
Result:
##id
eligibility | ||
---|---|---|
Eligible for VIP discount | 2 | |
Not eligible for VIP discount | ##3 | Peter Parker |
Other usages: |
Update records:
UPDATE table_name SET column_name = value WHERE condition;
The above is the detailed content of How to use if in sql. For more information, please follow other related articles on the PHP Chinese website!