Home  >  Article  >  Daily Programming  >  How to use oracle decode function in mysql

How to use oracle decode function in mysql

下次还敢
下次还敢Original
2024-04-27 06:00:291218browse

In MySQL, you can use CASE expressions to implement functions similar to Oracle's DECODE function: determine conditions and return values; use CASE expressions to list conditions and return values; add ELSE statements to specify default values.

How to use oracle decode function in mysql

Usage of Oracle DECODE function in MySQL

Oracle's DECODE function is a case statement used in Returns different values ​​under given conditions. There is no direct equivalent to the DECODE function in MySQL. However, you can use CASE expressions to achieve similar functionality.

Syntax

<code class="sql">CASE
    WHEN condition1 THEN value1
    WHEN condition2 THEN value2
    ...
    ELSE default_value
END</code>

Usage

  1. Determine the conditions and return value:First, Determine the conditions for comparison and the value to return if each condition is met.
  2. Use CASE expressions: Use the CASE keyword at the beginning of the expression, and then list each condition and its corresponding return value.
  3. Add an ELSE statement: Add an ELSE statement to specify a default value if any condition is not met.

Example

The following example demonstrates how to use the CASE expression to implement the DECODE function in MySQL:

<code class="sql">SELECT
    CASE
        WHEN age < 18 THEN "Minor"
        WHEN age >= 18 AND age < 65 THEN "Adult"
        ELSE "Senior"
    END AS age_category
FROM people;</code>

Result:

##Minor AdultSenior
age_category

Note:

CASE expression support in MySQL Use multiple WHEN clauses as well as ELSE clauses. Therefore, you can add additional conditions as needed.

The above is the detailed content of How to use oracle decode function in mysql. 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