Home > Database > SQL > body text

Conditional judgment statements in sql

下次还敢
Release: 2024-04-28 11:36:13
Original
433 people have browsed it

There are two common conditional judgment statements in SQL: IF-ELSE statement and CASE statement. The IF-ELSE statement executes different statements depending on whether the condition is true or false, while the CASE statement executes the corresponding statement depending on whether the expression value matches different conditions.

Conditional judgment statements in sql

Conditional judgment statement in SQL

Conditional judgment statement is evaluated in SQL Statements that condition and take different actions based on the results. They are widely used in SQL queries and operations to filter data from the database, modify data, or control processes.

Type

There are two commonly used conditional judgment statements in SQL:

  • IF-ELSE statement: Evaluates a condition and executes one statement if the condition is true, otherwise executes another statement.
  • CASE Statement: Evaluate a condition and execute the corresponding statement based on different condition values.

Syntax

IF-ELSE statement

<code class="sql">IF <condition> THEN
  <statement_if_true>
ELSE
  <statement_if_false>
END IF;</code>
Copy after login

CASE statement

<code class="sql">CASE <expression>
  WHEN <case_value1> THEN <statement1>
  WHEN <case_value2> THEN <statement2>
  ...
  ELSE <default_statement>
END CASE;</code>
Copy after login

Example

Use the IF-ELSE statement to check if the value is greater than 5

<code class="sql">SELECT *
FROM table_name
WHERE value IF value > 5 THEN 'Greater than 5' ELSE 'Less than or equal to 5' END IF;</code>
Copy after login

Use the CASE statement to check the score range

<code class="sql">CASE score
  WHEN 90 TO 100 THEN '优秀'
  WHEN 80 TO 89 THEN '良好'
  WHEN 70 TO 79 THEN '中等'
  ELSE '不及格'
END CASE;</code>
Copy after login

The above is the detailed content of Conditional judgment statements in sql. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template