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
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
trueor any non-null value is treated as true — onlynulland booleanfalseare treated as false. In the 4.0 series starting with 4.0.2609.0,null, booleanfalse, the numbers0andNaN, 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.
-
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 -
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 -
Condition is false — second expression is returned
table limit=5 WEB_APACHE_SAMPLE | eval result = if(method == "GET", "read", "write") | fields method, result -
NULL input — null condition is treated as false
json "{'val': null}" | eval result = if(val, "present", "absent") | # result: absent -
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: falseIn 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 number0is treated as false, so the result is"false"instead.
Change history
| Target | Introduced in |
|---|---|
The if() function | Before Sonar 4.0 |
Unified truthiness criteria — the number 0, empty strings, and so on are treated as false | 4.0.2609.0 |