Home > Database > Mysql Tutorial > How Does the SQL CASE Expression Work and What is its Syntax?

How Does the SQL CASE Expression Work and What is its Syntax?

Mary-Kate Olsen
Release: 2025-01-11 08:41:41
Original
525 people have browsed it

How Does the SQL CASE Expression Work and What is its Syntax?

SQL CASE expression syntax

SQL CASE expressions, also known as "CASE WHEN statements", allow you to evaluate multiple conditions and return different values ​​based on the results. Its syntax varies depending on the database engine used.

SQL Server syntax:

  • Case expression syntax:
<code class="language-sql">CASE case-expression
    WHEN when-expression-1 THEN value-1
  [ WHEN when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END</code>
Copy after login
  • Boolean expression syntax:
<code class="language-sql">CASE
    WHEN boolean-when-expression-1 THEN value-1
  [ WHEN boolean-when-expression-n THEN value-n ... ]
  [ ELSE else-value ]
END</code>
Copy after login

Among them:

  • case-expression: Evaluates a value or Boolean condition.
  • when-expression-x: Evaluates a value or Boolean condition that is compared to the case-expression.
  • value-1: Return this value if when-expression is equal to case-expression, or if boolean when-expression is TRUE.
  • boolean-when-expression: evaluates to TRUE or FALSE.
  • else-value: This value is returned if no match is found in the WHEN condition and no ELSE clause is specified.

Note that the order of the WHEN clauses is important and the first match is used. If no ELSE clause is provided and no matching WHEN condition is met, the result will be NULL.

The above is the detailed content of How Does the SQL CASE Expression Work and What is its Syntax?. 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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template