safe_add
Use the safe_add() function to perform addition of two numeric values with overflow protection. Unlike the standard add() function, safe_add() returns null instead of raising an error when the result overflows.
Syntax
safe_add(<number1>, <number2>)Parameters
number1
integer, float
Yes
The first numeric value to add.
number2
integer, float
Yes
The second numeric value to add.
Returns
Type: integer or float (matches input types)
Description: The safe_add() function returns the sum of the two input values. If the result would overflow the numeric type, the function returns null instead of raising an error. If either input is null, the function returns null.
Usage notes
Input type: XQL doesn't support NaN or infinite values as input and these value types also can not be returned.
Overflow Protection: The primary advantage of
safe_add()overadd()is that it returnsnullinstead of raising an error when the result exceeds the maximum or minimum value of the numeric type.Null Handling: If either input expression is
null, the function returnsnull.Type Preservation: When both inputs are integers, the result is an integer. When either input is a float, the result is a float.
Common Use Cases: This function is used when working with potentially large numbers where overflow is a concern, such as summing large counters, byte counts, or accumulated metrics.
Examples
Example 1: Safe addition of literal values
Goal: Perform safe addition on numeric literals, including cases that might overflow.
XQL code:
Explanation: safe_add(100, 200) returns 300 as expected. safe_add(9223372036854775807, 1) would overflow the maximum 64-bit integer value, so it returns null instead of raising an error.
Output:
300
null
Example 2: Safe addition of field values
Goal: Safely add two numeric fields that might produce overflow.
XQL code:
Explanation: This query safely adds event_id and numeric_value for each record. If any combination would cause an overflow, the result is null rather than an error.
Output:
101
5.0
106.0
102
200.0
302.0
103
50.0
153.0
Example 3: Use safe_add with coalesce for fallback
Goal: Perform safe addition and provide a fallback value when the result is null due to overflow.
XQL code:
Explanation: This query uses safe_add() to add two fields, then applies coalesce() to replace any null results (from overflow or null inputs) with 0 as a fallback value.
Output:
101
5.0
106.0
106.0
102
200.0
302.0
302.0
103
50.0
153.0
153.0
Related articles
Functions:
add,safe_subtract,safe_multiply,coalesce
Last updated
Was this helpful?
