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. What counts as a true condition differs by series. In the 5.0 series (through 5.0.2605.2), boolean true or any non-null value is treated as true — only null and boolean false are treated as false. In the 4.0 series starting with 4.0.2609.0, null, boolean false, the numbers 0 and NaN, an empty string, and an empty list, array, or map are all treated as false, and every other value is treated as true.
EXPR_IF_TRUE
The value expression to return when the condition is treated as true.
EXPR_IF_FALSE
The value expression to return when the condition is treated as false.

Description

The if() function evaluates CONDITION, determining whether it is true or false, and returns EXPR_IF_TRUE or EXPR_IF_FALSE accordingly. What counts as true differs by series — see the CONDITION parameter above.

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
    
  5. Using the number 0 as a condition — result differs by series

    json "{'val': 0}" | eval result = if(val, "true", "false")
    | # 5.0 series (through 5.0.2605.2) result: true / 4.0 series (4.0.2609.0 and later) result: false
    

    In the 5.0 series (through 5.0.2605.2), any non-null value, including 0, is treated as true, so this example returns "true". In the 4.0 series starting with 4.0.2609.0, the number 0 is treated as false, so the result is "false" instead.

Change history

TargetIntroduced in
The if() functionBefore Sonar 4.0
Unified truthiness criteria — the number 0, empty strings, and so on are treated as false4.0.2609.0