if()

The if() function evaluates a condition expression and returns the first value if the condition is true, or the second value if it is false. It operates the same way as a ternary operator.

Syntax

if(CONDITION, EXPR_IF_TRUE, EXPR_IF_FALSE)

Parameters

CONDITION
The condition expression to evaluate. The condition is considered true if it evaluates to boolean true or to any non-null value.
EXPR_IF_TRUE
The value expression to return when the condition is true.
EXPR_IF_FALSE
The value expression to return when the condition is false or null.

Description

The if() function evaluates CONDITION. If the condition evaluates to boolean true or to any non-boolean, non-null value, the function returns EXPR_IF_TRUE. If the condition evaluates to boolean false or null, the function returns EXPR_IF_FALSE.

The return type is determined by the types of EXPR_IF_TRUE and EXPR_IF_FALSE. If the two 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 of 400 or above as errors

    table limit=5 WEB_APACHE_SAMPLE | eval result = if(status >= 400, "error", "ok") | fields status, result
    
  2. Branch based on whether the response size exceeds 1000 bytes

    table limit=5 WEB_APACHE_SAMPLE | eval label = if(bytes > 1000, "large", "small") | fields bytes, label
    
  3. Condition is false — second expression is returned

    table limit=5 WEB_APACHE_SAMPLE | eval result = if(method == "GET", "read", "write") | fields method, result
    
  4. NULL input — null condition is treated as false

    json "{'val': null}" | eval result = if(val, "present", "absent")
    | # result: absent
    

Compatibility

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