Home > Database > SQL > body text

How to use case function in sql

下次还敢
Release: 2024-04-28 09:45:24
Original
876 people have browsed it

SQL CASE function performs different operations by comparing expression results. Its syntax is: WHEN expression THEN result1WHEN expression THEN result2...[ELSE default_result]END

How to use case function in sql

Usage of CASE function in SQL

The CASE function is a powerful tool in SQL that is used to perform different operations based on the result of an expression. The syntax is as follows:

<code class="sql">CASE
  WHEN expression1 THEN result1
  WHEN expression2 THEN result2
  ...
  [ELSE default_result]
END</code>
Copy after login

Usage example

For example, to get an employee's salary range based on their department, you can use the CASE function:

<code class="sql">SELECT
  salary,
  CASE department
    WHEN 'Sales' THEN '25,000 - 50,000'
    WHEN 'Engineering' THEN '35,000 - 75,000'
    WHEN 'Marketing' THEN '20,000 - 40,000'
    ELSE 'Unknown'
  END AS salary_range
FROM
  employees;</code>
Copy after login

This will return the following results:

##50,00035,000 - 75,00025,00020,000 - 40,000
Salary Salary Range
30,000 25,000 - 50,000

Other Use Cases

There are many other use cases for the CASE function, including:

  • Verify data integrity: Verify whether the data meets certain conditions.
  • Convert data format: Convert data from one format to another.
  • Aggregate data: Group and summarize data according to different conditions.
  • Complex query: Perform different operations according to different situations in complex queries.

Note:

    The CASE statement can contain multiple WHEN clauses and an optional ELSE clause.
  • The ELSE clause can be used to specify the default result when all WHEN clauses are not satisfied.
  • CASE statements can be nested to create more complex conditions.

The above is the detailed content of How to use case function 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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!