【MySQL】CASE Function

MySQL: CASE Function

This MySQL tutorial explains how to use the MySQL CASE function with syntax and examples.

Description

The MySQL CASE function has the functionality of an IF-THEN-ELSE statement by allowing you to evaluate conditions and return a value when the first condition is met.

Syntax

The syntax for the CASE function in MySQL is:

CASE [ expression ]

   WHEN condition_1 THEN result_1
   WHEN condition_2 THEN result_2
   ...
   WHEN condition_n THEN result_n

   ELSE result

END

Parameters or Arguments

expression

Optional. It is the value that you are comparing to the list of conditions. (ie: condition_1, condition_2, ... condition_n)

condition_1, condition_2, ... condition_n

Evaluated in the order listed. Once a condition is found to be true, the CASE function will return the result and not evaluate the conditions any further.

result_1, result_2, ... result_n

The value returned once a condition is found to be true.

Note

  • If no condition is found to be true, then the CASE function will return the value in the ELSE clause.
  • If the ELSE clause is omitted and no condition is found to be true, then the CASE statement will return NULL.

Applies To

The CASE function can be used in the following versions of MySQL:

  • MySQL 5.7, MySQL 5.6, MySQL 5.5, MySQL 5.1, MySQL 5.0, MySQL 4.1, MySQL 4.0, MySQL 3.23.3

Example - Includes expression

You could use the CASE function in a SQL statement where the expression is included.

SELECT supplier_id,
CASE quantity
  WHEN > 10 THEN 'The quantity is greater than 10'
  WHEN = 10 THEN 'The quantity is 10'
  ELSE 'The quantity is something else'
END
FROM suppliers;

In this CASE function example, the expression is quantity whose value would be compared to each of the conditions until one is met. Then the corresponding value would be returned by the CASE function.

Example - Excludes expression

You could use the CASE function in a SQL statement where the expression is omitted.

SELECT
CASE
  WHEN a < b THEN 1
  WHEN supplier_type = 'clothing' THEN 2
  ELSE 3
END
FROM suppliers;

In this CASE function example, an expression has not been included so each condition is individually evaluated and can be completely different and unique. When a condition is met, the corresponding value would be returned.

[From Google: https://www.techonthenet.com/mysql/functions/case.php]

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值