Outdated Version

You are viewing an older version of this section. View current production version.

CASE

Switch statement construct. There are two species of CASE statement. The first is a collection of independent “WHEN” conditions. The first to evaluate true returns its value. The second uses only one expression or condition, and returns the first “WHEN” clause which equals the expression.

Syntax

(CASE
  WHEN condition THEN val1
  WHEN condition THEN val2
  ...
  ELSE defaultval END)

Switching off a single expression:

(CASE expression
  WHEN case1 THEN val1
  WHEN case2 THEN val2
  ...
  ELSE defaultval END)

Arguments

  • Any SQL objects

Return Type

The return type depends on the type of arguments val1, val2, etc. For example, if val1 or val2 is an integer, the return type will be an integer, depending on which condition is met. If they are both strings, the return type will be a string, and so on.

Examples

memsql> select (case                                                                              
    -> when 1=0 then 3
    -> when 0=1 then 5
    -> else 8 end) as choices;
+---------+
| choices |
+---------+
|       8 |
+---------+
1 row in set (0.21 sec)

memsql> select (case 'ohai'
     ->  when 'yo' then 'sup'
     ->  when 'hello' then 'hi'
     ->  when 'ohai' then 'bai'
     ->  else 'huh?' end) as greeting;
+----------+
| greeting |
+----------+
| bai      |
+----------+
``` `