Home  >  Article  >  Database  >  How to use if in sql

How to use if in sql

下次还敢
下次还敢Original
2024-05-01 22:45:28952browse

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.

How to use if in sql

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:

  1. ##Condition (condition): A Boolean expression used to evaluate the condition authenticity.
  2. True statement block (true_statement): SQL statement executed if the condition is true.
  3. False statement block (false_statement) (optional): SQL statement to be executed if the condition is false.

Example:

Suppose we have a table named

customers which contains the following data:

idnameage##12##3Peter Parker18To get only customer information older than 25 years old, we can use the following SQL query:
<code class="sql">SELECT * FROM customers
WHERE age > 25;</code>
John Doe 30
Jane Smith 25
However, using IF statements, we can dynamically display different messages based on age. For example:

<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:

##idname1John DoeJane Smith##3Peter ParkerNot eligible for VIP discountOther usages:
eligibility
Eligible for VIP discount 2
Not eligible for VIP discount
IF statement is also used in SQL:

Update records:

UPDATE table_name SET column_name = value WHERE condition;

    Delete records:
  • DELETE FROM table_name WHERE condition;
  • Set variables:
  • SET @variable_name = expression 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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:Usage of is null in sqlNext article:Usage of is null in sql