ARRAY_AGGREGATE Function
Overview
ARRAY_AGGREGATE is a higher-order array aggregation function, similar to the reduce / fold operation in functional programming. It receives an array, an initial value, and a merge lambda expression. Starting from the initial value, it sequentially merges each element of the array with the accumulator using the merge lambda, ultimately returning the aggregated result.
Syntax
Parameters
array: The input array, of typeARRAY<E>, where E can be any data type.initial_value: The initial value for aggregation (initial accumulator state), of typeR, which can be any data type.merge_lambda: The merge lambda expression, in the format(acc, x) -> expr, whereaccis the current accumulator value (typeR),xis the current element in the array (typeE), andexpris the new accumulator value (typeR).
Returns
The return type matches the type of initial_value (type R), i.e., the return type of the merge lambda expression.
Examples
-
Compute the sum of array elements:
-
Merge nested arrays into a single deduplicated array:
-
Count the total number of distinct elements across nested arrays:
-
Use a boolean accumulator to check if all array elements satisfy a condition:
-
When array elements contain uncastable values, NULL propagates through the lambda:
Notes
- Before using the ARRAY_AGGREGATE function, JIT code generation must be enabled:
SET cz.sql.codegen.enable = TRUE;. - When the input array is NULL, the result is NULL.
- When the array is empty, the initial value
initial_valueis returned. - If the merge lambda produces a NULL value, NULL will continue to participate in subsequent iterations, potentially causing the final result to be NULL. It is recommended to use functions like
COALESCEin the lambda to handle NULL values. - The type of the initial value determines the type of the accumulator and the final return value. Ensure the return type of the merge lambda is compatible with the initial value type.
