CASE

2023-07-28 02:55:42  Updated

Syntax

CASE value WHEN compare-value THEN result [WHEN [compare-value] THEN result ...] [ELSE result] END
CASE WHEN condition THEN result [WHEN [condition] THEN result ...] [ELSE result] END

Purpose

In the returned result of the first syntax, value= compare-value. The prerequisite of the returned result of the second syntax is that the first condition is true. If no matching result exists, the returned result is the result after the ELSE operation. If no ELSE operation is involved, the return value is NULL.

Examples

obclient> SELECT CASE 'B' WHEN 'A' THEN 1 WHEN 'B' THEN 2 END;
+----------------------------------------------+
| CASE 'B' WHEN 'A' THEN 1 WHEN 'B' THEN 2 END |
+----------------------------------------------+
|                                            2 |
+----------------------------------------------+
1 row in set

obclient> SELECT CASE CONCAT('A','B') WHEN CONCAT('AB','') THEN 'A' WHEN 'B' THEN 'B' END;
+--------------------------------------------------------------------------+
| CASE CONCAT('A','B') WHEN CONCAT('AB','') THEN 'A' WHEN 'B' THEN 'B' END |
+--------------------------------------------------------------------------+
| A                                                                        |
+--------------------------------------------------------------------------+
1 row in set

obclient> SELECT CASE WHEN 1>0 THEN 'TRUE' ELSE 'FALSE' END;
+--------------------------------------------+
| CASE WHEN 1>0 THEN 'TRUE' ELSE 'FALSE' END |
+--------------------------------------------+
| TRUE                                       |
+--------------------------------------------+
1 row in set

Contact Us