General Functions (aggregate functions)

Part of the datafusion-spark function reference.

avg

Returns the average of the non-NULL values as a DOUBLE, or NULL if there are none. All numeric input is cast to DOUBLE first. So unlike DataFusion‘s avg and Spark’s, DECIMAL input returns a DOUBLE rather than a DECIMAL (#111).

avg(expr)

Arguments

  • expr: Numeric expression to average. NULL values are skipped.

Example

> SELECT avg(a) FROM (VALUES (40), (23), (17), (40), (NULL)) AS t(a);
30

collect_list

Returns an array of the non-NULL values, including duplicates. Unlike DataFusion's array_agg, NULL values are skipped, so a group or window frame that is empty or holds only NULLs returns an empty array, where array_agg returns NULL or an array of NULLs. The order of the elements depends on the order of the rows, which may not be deterministic. ORDER BY inside the call is not supported and fails with an internal error (#112).

collect_list(expr)

Arguments

  • expr: Expression of any type to collect. NULL values are skipped.

Example

> SELECT collect_list(a) FROM (VALUES (1), (2), (NULL), (1)) AS t(a);
[1, 2, 1]
> SELECT collect_list(a) FROM (VALUES (CAST(NULL AS INT))) AS t(a);
[]

collect_set

Returns an array of the distinct non-NULL values, in no particular order. Unlike DataFusion's array_agg(DISTINCT ...), NULL values are skipped, so a group or window frame that is empty or holds only NULLs returns an empty array, where array_agg returns NULL or [NULL].

collect_set(expr)

Arguments

  • expr: Expression of any type to collect. NULL values are skipped.

Example

> SELECT array_sort(collect_set(a)) FROM (VALUES (1), (2), (NULL), (2)) AS t(a);
[1, 2]
> SELECT collect_set(a) FROM (VALUES (CAST(NULL AS INT))) AS t(a);
[]

try_sum

Returns the sum of the non-NULL values, or NULL if the sum overflows. DataFusion has no built-in try_sum. Integer input returns BIGINT, floating-point input returns DOUBLE, and DECIMAL(p, s) returns DECIMAL(min(p + 10, 38), s). BIGINT and DECIMAL overflow returns NULL, while DOUBLE sums follow IEEE 754 and can return Infinity or NaN. Returns NULL if all values are NULL. Other input types, such as intervals, are not supported.

try_sum(expr)

Arguments

  • expr: Integer, floating-point or decimal expression to sum. NULL values are skipped.

Example

> SELECT try_sum(x) FROM VALUES (1), (2), (3) AS tab(x);
6
> SELECT try_sum(x) FROM VALUES (CAST(9223372036854775807 AS BIGINT)), (1) AS tab(x);
NULL