case()

The case() function evaluates condition-value pairs in order and returns the value corresponding to the first condition that evaluates to true. If no condition is true, it optionally returns a default value.

Syntax

case(COND1, VAL1[, COND2, VAL2, ...[, DEFAULT]])

Parameters

COND1, COND2, ...
Condition expressions evaluated in order. A condition is considered true if it evaluates to boolean true or to any non-null value.
VAL1, VAL2, ...
Value expressions to return when the corresponding condition is true. Each value is paired with its corresponding condition.
DEFAULT
(Optional) The default value to return when all conditions are false. If the total number of arguments is odd, the last argument is used as the default value.

Description

The case() function evaluates conditions in the order COND1, COND2, .... A condition is considered true if it evaluates to boolean true or to any non-boolean, non-null value. When a true condition is found, the function immediately returns its corresponding value without evaluating further conditions.

If no condition is true, the function returns the DEFAULT value if specified, or null if no default is provided.

If a condition evaluates to boolean false or null, evaluation continues to the next condition.

The return type is determined by the type of the value expression that was actually evaluated. If the value expressions have different types, the result is automatically promoted to a common supertype (for example, a mix of integer and float values returns a float).

Error codes

N/A

Usage examples

To prepare the WEB_APACHE_SAMPLE table used in these examples, refer to Preparing sample data.

  1. Classify HTTP status codes into labels by range

    table limit=5 WEB_APACHE_SAMPLE
    | eval label = case(status >= 500, "Server Error", status >= 400, "Client Error", status >= 300, "Redirect", "OK")
    | fields status, label
    | # label is determined based on the status value.
    
  2. Classify by HTTP method

    table limit=5 WEB_APACHE_SAMPLE
    | eval type = case(method == "GET", "Read", method == "POST", "Submit", method == "OPTIONS", "Preflight", "Other")
    | fields method, type
    
  3. No condition matches and no default is provided

    json "{'val': 0}" | eval result = case(val == 1, "one", val == 2, "two")
    | # result: null
    
  4. NULL input — null is treated as false during condition evaluation, so the default value is returned

    json "{'val': null}" | eval result = case(val == 1, "one", "default")
    | # result: default
    

Compatibility

The case() function is available since before Sonar 4.0.