Home > Database > Mysql Tutorial > How Can I Use MySQL\'s CASE Statement to Assign Values Based on Conditions?

How Can I Use MySQL\'s CASE Statement to Assign Values Based on Conditions?

DDD
Release: 2024-11-08 12:59:02
Original
556 people have browsed it

How Can I Use MySQL's CASE Statement to Assign Values Based on Conditions?

MySQL CASE Syntax Explained

SQL's CASE statement allows you to conditionally execute different sets of statements based on specific conditions. It's not an if-else statement; rather, it's more analogous to a switch statement.

To understand how CASE works, consider the following example:

Problem:

You have a field named user_role in the user table, which contains user roles such as "Manager", "Part Time", etc. You need to generate a new field named role_order that assigns a different number to each role. For instance, if user_role = 'Manager', then role_order should be 5.

Solution:

Using the CASE syntax, you can implement this logic as follows:

<code class="sql">CASE 
    WHEN user_role = 'Manager' then 5
    WHEN user_role = 'Part Time' then 7
    ELSE -1 --unknown
END</code>
Copy after login

Here, the CASE statement:

  • Examines the value of the user_role field
  • If it equals 'Manager', it returns 5
  • If it equals 'Part Time', it returns 7
  • If it doesn't match any of the specified values, it returns -1 (representing an unknown role)

Another Syntax Option:

If you're only examining a single value, you can use a more concise syntax:

<code class="sql">CASE user_role
    WHEN 'Manager' then 5
    WHEN 'Part Time' then 7
    ELSE -1 --unknown
END</code>
Copy after login

Remember, CASE allows you to evaluate multiple conditions and conditionally execute different statements. It's a powerful tool for managing conditional logic in SQL queries.

The above is the detailed content of How Can I Use MySQL\'s CASE Statement to Assign Values Based on Conditions?. 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