SQL CASE function performs different operations by comparing expression results. Its syntax is: WHEN expression THEN result1WHEN expression THEN result2...[ELSE default_result]END
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>
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>
This will return the following results:
Salary | Salary Range |
---|---|
30,000 | 25,000 - 50,000 |
35,000 - 75,000 | |
20,000 - 40,000 |
Other Use Cases
There are many other use cases for the CASE function, including:Note:
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!