Home  >  Article  >  Database  >  Usage of casewhen in sql

Usage of casewhen in sql

下次还敢
下次还敢Original
2024-04-28 11:42:16805browse

The CASE WHEN statement is used to return different values ​​based on conditions. Its usage steps are: Specify conditions: Determine the conditions to be evaluated. Specifies the result: the value returned if the condition is true. Specify an ELSE clause: If no condition is true, a default value is returned (optional).

Usage of casewhen in sql

Usage of CASE WHEN statement in SQL

The CASE WHEN statement is a conditional statement in SQL query language An expression that returns a different value based on specified conditions. The syntax is as follows:

<code class="sql">CASE
  WHEN condition1 THEN result1
  WHEN condition2 THEN result2
  ...
  ELSE default_result
END</code>

Usage steps:

  1. Specify conditions (condition): Determine the conditions to be evaluated.
  2. Specify the result (result): The value returned if the condition is true.
  3. Specify the ELSE clause: If no condition is true, return the default value (optional).

Example:

<code class="sql">SELECT CASE
  WHEN age > 18 THEN '成年'
  WHEN age >= 13 AND age <= 18 THEN '青少年'
  ELSE '儿童'
END AS age_category
FROM students;</code>

Result:

##1John20Adult2Mary16teenager3Peter10Children
Student ID Name Age Age Category

Other uses:

  • Return NULL value: The ELSE clause can be set to NULL to return a null value when no condition is true.
  • Nested CASE WHEN statements: CASE WHEN statements can be nested to handle more complex conditions.
  • Use CASE expressions as filter conditions: You can use CASE expressions in the WHERE clause to filter data.

Advantages:

    Simplifies queries with complex conditions.
  • Improves the performance of queries because the server does not need to execute multiple IF-THEN statements.
  • Provides a concise way to handle different situations in SQL queries.

The above is the detailed content of Usage of casewhen 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