View a markdown version of this page

Sum and average functions - Amazon Athena

Sum and average functions

Use these functions to add up, multiply, or average the values in a group. Besides sum and avg, they include weighted and geometric averages, an average that keeps the DECIMAL type, and a sum and an average that reduce floating-point rounding error.

avg function

Returns the arithmetic mean of the non-NULL values of x: their sum divided by how many there are. NULL values are skipped, not counted as zero. If every value is NULL, or if there are no input rows, the result is NULL.

For numeric input, including DECIMAL, the result is a DOUBLE. You can also average INTERVAL, TIME, and TIMESTAMP values, and the result then has the type of x.

mean is an alias of avg.

Syntax

avg(x)

Arguments

The avg function takes the following argument:

x

The values to average. A numeric value, such as INTEGER, BIGINT, DOUBLE, or DECIMAL, or an INTERVAL, TIME, TIME WITH TIME ZONE, TIMESTAMP, or TIMESTAMP WITH TIME ZONE value.

Return type

DOUBLE for numeric input, including DECIMAL. For INTERVAL, TIME, TIME WITH TIME ZONE, TIMESTAMP, and TIMESTAMP WITH TIME ZONE input, the type of x.

Examples

The following SQL query averages four rows, one of them NULL. The NULL is skipped, so the result is the sum, 9, divided by 3.

SELECT avg(x) AS result FROM (VALUES (1), (2), (NULL), (6)) AS v(x)

The query returns the following result.

result

3.0

The following SQL query averages DECIMAL(10,2) values. The result is a DOUBLE, and the cast returns a DECIMAL(10,2).

SELECT avg(amount) AS avg_double, CAST(avg(amount) AS DECIMAL(10, 2)) AS avg_decimal FROM (VALUES (CAST(10.25 AS DECIMAL(10, 2))), (CAST(20.50 AS DECIMAL(10, 2))), (CAST(30.01 AS DECIMAL(10, 2))) ) AS v(amount)

The query returns the following result.

avg_double avg_decimal

20.253333333333334

20.25

The following SQL query uses the mean alias to average two INTERVAL values. The result is an INTERVAL of 1 hour and 30 minutes.

SELECT mean(duration) AS result FROM (VALUES (INTERVAL 1 HOUR), (INTERVAL 2 HOUR) ) AS v(duration)

The query returns the following result.

result

01:30:00

Considerations

avg does not convert strings to numbers. A VARCHAR column that holds numbers makes the query fail, so cast it first, as in avg(CAST(x AS DOUBLE)).

Because the result of a DECIMAL average is a DOUBLE, it can have many digits after the decimal point. To get a fixed number of digits, cast the result, as in CAST(avg(amount) AS DECIMAL(10, 2)).

Differences from Athena engine version 3

In Athena engine version 3, avg of a DECIMAL value returns a DECIMAL. In DuckDB, it returns a DOUBLE. To get a DECIMAL result, cast it to the type that you need, as in CAST(avg(amount) AS DECIMAL(10, 2)).

decimal_average function

Returns the average of the values of expression that are not NULL, and keeps the DECIMAL type of the input, so a DECIMAL(18,2) input gives a DECIMAL(18,2) result. The function never converts the values to floating point, so the sum is exact and only the final division rounds. When the exact average is halfway between two values at the input scale, the function rounds to the value whose last digit is even. For example, the average of 1.00 and 1.05 is 1.02.

Use decimal_average when you need the average of DECIMAL values as a DECIMAL. avg of a DECIMAL returns a DOUBLE. If there are no values that are not NULL, the result is NULL.

Syntax

decimal_average(expression)

Arguments

The decimal_average function takes the following argument:

expression

The values to average, as a DECIMAL value. Cast other numeric types first, for example CAST(x AS DECIMAL(18,2)).

Return type

DECIMAL with the same precision and scale as expression, for example DECIMAL(18,2) for a DECIMAL(18,2) input.

Examples

The following SQL query averages two values as DECIMAL(18,2). The exact average is 1.875, which is halfway between 1.87 and 1.88, so the function returns 1.88, the value with the even last digit.

SELECT decimal_average(CAST(x AS DECIMAL(18, 2))) AS result FROM (VALUES (1.5), (2.25)) AS v(x)

The query returns the following result.

result

1.88

The following SQL query shows the result types of avg and decimal_average for the same DECIMAL(10,2) input.

SELECT typeof(avg(x)) AS avg_type, typeof(decimal_average(x)) AS decimal_average_type FROM (VALUES (CAST(1.50 AS DECIMAL(10, 2))), (CAST(2.25 AS DECIMAL(10, 2))) ) AS v(x)

The query returns the following result.

avg_type decimal_average_type

DOUBLE

DECIMAL(10,2)

The following SQL query averages 2 and 3 at two scales. At scale 0, the exact average 2.5 rounds to the even value 2. At scale 1, the result keeps the decimal place.

SELECT decimal_average( CAST(x AS DECIMAL(10, 0)) ) AS scale_0, decimal_average( CAST(x AS DECIMAL(10, 1)) ) AS scale_1 FROM (VALUES (2), (3)) AS v(x)

The query returns the following result.

scale_0 scale_1

2

2.5

Considerations

decimal_average accepts only DECIMAL values. An INTEGER, BIGINT, or DOUBLE argument makes the query fail, so cast it to DECIMAL first.

The result keeps the scale of the input, so it can have fewer decimal places than the exact average. To keep more digits, cast the input to a DECIMAL with a larger scale.

Differences from Athena engine version 3

In Athena engine version 3, avg of a DECIMAL column returns a DECIMAL of the same type, and rounds a halfway result away from zero. In DuckDB, avg returns DOUBLE. The decimal_average function keeps the DECIMAL type but rounds a halfway result to the even digit, so the last digit can differ. For 1.00 and 1.05, avg in Athena engine version 3 returns 1.03, and decimal_average returns 1.02.

favg function

Returns the average of the values of expression that are not NULL, like avg, but adds the values with Kahan summation. Kahan summation keeps track of the rounding error of each addition and adds it back, so small values are not lost when the input also has very large values.

If there are no values that are not NULL, the result is NULL. To get the sum instead of the average, use the kahan_sum function.

Syntax

favg(expression)

Arguments

The favg function takes the following argument:

expression

The values to average, as a DOUBLE value. Other numeric types are converted to DOUBLE.

Return type

DOUBLE

Examples

The following SQL query returns the average of three values.

SELECT favg(x) AS result FROM (VALUES (1), (4), (7)) AS v(x)

The query returns the following result.

result

4.0

The following SQL query has two very large values that cancel out and two small values. The exact average is (1 + 1) / 4, or 0.5. Because Kahan summation keeps the two small values, favg returns that average.

SELECT favg(x) AS result FROM (VALUES (1e16), (1), (1), (-1e16)) AS v(x)

The query returns the following result.

result

0.5

The following SQL query skips the NULL value and averages the other two values.

SELECT favg(x) AS result FROM (VALUES (1), (NULL), (4)) AS v(x)

The query returns the following result.

result

2.5

geomean function

Returns the geometric mean of the values of expression that are not NULL: the nth root of the product of n values. The function computes it as exp(avg(ln(expression))). Use it for values that combine by multiplication, such as growth factors.

If there are no values that are not NULL, the result is NULL. geometric_mean returns the same result.

Syntax

geomean(expression)

Arguments

The geomean function takes the following argument:

expression

The values whose geometric mean the function returns, as a positive numeric value. The value is converted to DOUBLE.

Return type

DOUBLE

Examples

The following SQL query returns the geometric mean of 2, 4, and 8, which is the cube root of their product, 64.

SELECT geomean(x) AS result FROM (VALUES (2), (4), (8)) AS v(x)

The query returns the following result.

result

4.0

The following SQL query returns the average growth factor of three periods that grew by 10 percent, grew by 20 percent, and shrank by 10 percent. The result is rounded to four decimal places.

SELECT round(geomean(x), 4) AS result FROM (VALUES (1.10), (1.20), (0.90)) AS v(x)

The query returns the following result.

result

1.0591

The following SQL query includes a 0, which makes the result 0.0.

SELECT geomean(x) AS result FROM (VALUES (2), (0), (8)) AS v(x)

The query returns the following result.

result

0.0

The following SQL query includes a negative value, which makes the result NaN.

SELECT isnan(geomean(x)) AS is_nan FROM (VALUES (2), (-1), (8)) AS v(x)

The query returns the following result.

is_nan

true

Considerations

Because the function takes the natural logarithm of each value, use it only for positive values. A value of 0 makes the result 0, and a negative value makes the result NaN.

geometric_mean function

Returns the geometric mean of the values of expression that are not NULL: the nth root of the product of n values. The expression geometric_mean(expression) is defined as geomean(expression), so the two functions return the same result.

If there are no values that are not NULL, the result is NULL.

Syntax

geometric_mean(expression)

Arguments

The geometric_mean function takes the following argument:

expression

The values whose geometric mean the function returns, as a positive numeric value. The value is converted to DOUBLE.

Return type

DOUBLE

Examples

The following SQL query returns the geometric mean of 2, 4, and 8.

SELECT geometric_mean(x) AS result FROM (VALUES (2), (4), (8)) AS v(x)

The query returns the following result.

result

4.0

The following SQL query skips the NULL value and returns the geometric mean of 2 and 8.

SELECT geometric_mean(x) AS result FROM (VALUES (2), (NULL), (8)) AS v(x)

The query returns the following result.

result

4.0

Considerations

Because the function takes the natural logarithm of each value, use it only for positive values. A value of 0 makes the result 0, and a negative value makes the result NaN.

kahan_sum function

Returns the sum of the values of expression that are not NULL, as a DOUBLE. The function adds the values with Kahan summation, which keeps track of the rounding error of each addition and adds it back. As a result, small values are not lost next to very large ones. For the same DOUBLE input, the result can differ from the result of sum.

If there are no values that are not NULL, the result is NULL. To get the average instead of the sum, use the favg function.

fsum and sumkahan are aliases of kahan_sum.

Syntax

kahan_sum(expression)

Arguments

The kahan_sum function takes the following argument:

expression

The values to add, as a DOUBLE value. Other numeric types are converted to DOUBLE.

Return type

DOUBLE

Examples

The following SQL query returns the sum of three values.

SELECT kahan_sum(x) AS result FROM (VALUES (1), (4), (7)) AS v(x)

The query returns the following result.

result

12.0

The following SQL query adds 1e16, 1, and -1e16. Adding them from left to right with ordinary floating-point arithmetic loses the 1, as the plain_result column shows. kahan_sum keeps it.

SELECT (1e16 + 1) - 1e16 AS plain_result, kahan_sum(x) AS kahan_result FROM (VALUES (1e16), (1), (-1e16)) AS v(x)

The query returns the following result.

plain_result kahan_result

0.0

1.0

The following SQL query uses the fsum alias on DECIMAL values. The result is a DOUBLE.

SELECT fsum(x) AS result FROM (VALUES (CAST(1.25 AS DECIMAL(10, 2))), (CAST(2.50 AS DECIMAL(10, 2))) ) AS v(x)

The query returns the following result.

result

3.75

Considerations

kahan_sum returns DOUBLE even for INTEGER and DECIMAL input. For an exact sum of DECIMAL values, use the sum function.

product function

Returns the product of the values of arg in the group, as a DOUBLE. NULL values are ignored. If the group has no values that are not NULL, the result is NULL.

One use is to compound growth rates. The product of 1 + rate over a series of rates is the total growth factor.

Syntax

product(arg)

Arguments

The product function takes the following argument:

arg

The values to multiply, as numeric values. The function converts them to DOUBLE.

Return type

DOUBLE

Examples

The following SQL query multiplies three integers. The result is a DOUBLE.

SELECT product(x) AS result FROM (VALUES (1), (4), (7)) AS v(x)

The query returns the following result.

result

28.0

The following SQL query ignores the NULL value and multiplies the other two values.

SELECT product(x) AS result FROM (VALUES (2), (NULL), (5)) AS v(x)

The query returns the following result.

result

10.0

The following SQL query compounds three period returns of 5 percent, 10 percent, and -2 percent into a total growth factor, rounded to four decimal places.

SELECT round(product(1 + rate), 4) AS growth_factor FROM (VALUES (0.05), (0.10), (-0.02)) AS v(rate)

The query returns the following result.

growth_factor

1.1319

The following SQL query multiplies two 9-digit integers. The exact product has 18 digits, more than a DOUBLE holds exactly, so the result does not equal the exact BIGINT product.

SELECT CAST( product(x) AS BIGINT ) = CAST(123456789 AS BIGINT) * 987654321 AS is_exact FROM (VALUES (123456789), (987654321)) AS v(x)

The query returns the following result.

is_exact

false

Considerations

Because the result is a DOUBLE, it holds only about 15 to 17 significant digits. A product of integers that needs more digits is rounded, so the result can differ from the exact integer product.

sum function

Returns the total of the non-NULL values of arg. If every value is NULL, or the group has no rows, the result is NULL, not 0. To get 0 instead, use coalesce(sum(arg), 0).

For integer input, the result is a HUGEINT, a 128-bit integer, so a sum of BIGINT values does not overflow. For BOOLEAN input, sum counts the true values.

Syntax

sum([ DISTINCT ] arg)

Arguments

The sum function takes the following argument:

arg

The values to add, of a numeric type (TINYINT, SMALLINT, INTEGER, BIGINT, HUGEINT, BIGNUM, DECIMAL, FLOAT, or DOUBLE), or BOOLEAN. With DISTINCT, each distinct value is added once.

Return type

HUGEINT for BOOLEAN and integer input up to HUGEINT; DECIMAL(38, s) for DECIMAL input with scale s; DOUBLE for FLOAT and DOUBLE input; and BIGNUM for BIGNUM input.

Examples

The following SQL query adds three integers. The result is a HUGEINT.

SELECT sum(x) AS result FROM (VALUES (1), (4), (7)) AS t(x)

The query returns the following result.

result

12

The following SQL query has only NULL values, so sum returns NULL. coalesce replaces that NULL with 0.

SELECT sum(x) AS total, coalesce(sum(x), 0) AS total_or_zero FROM (VALUES (CAST(NULL AS INTEGER)), (NULL)) AS t(x)

The query returns the following result.

total total_or_zero

NULL

0

The following SQL query adds two copies of the largest BIGINT value. The total does not fit in a BIGINT, but the query still returns it because the result is a HUGEINT.

SELECT sum(x) AS result FROM (VALUES (CAST(9223372036854775807 AS BIGINT)), (CAST(9223372036854775807 AS BIGINT)) ) AS t(x)

The query returns the following result.

result

18446744073709551614

The following SQL query adds three DECIMAL values with two digits after the decimal point. The result is a DECIMAL(38,2), so it keeps the two digits after the decimal point.

SELECT sum(amount) AS result FROM (VALUES (120.50), (75.00), (42.25)) AS t(amount)

The query returns the following result.

result

237.75

Considerations

A Hive table cannot store a HUGEINT column. When you write a sum of integers to a Hive table, for example with CREATE TABLE AS or INSERT INTO, cast it, as in CAST(sum(arg) AS BIGINT). An Iceberg table stores a HUGEINT as DECIMAL(38, 0).

sum does not convert strings to numbers. Cast a VARCHAR column first, for example sum(CAST(arg AS DECIMAL(10,2))).

A sum of DOUBLE values is computed in floating point, so it can differ from the exact decimal total in the last digits. For example, the sum of 0.1 and 0.2 as DOUBLE values is 0.30000000000000004. Use DECIMAL values for exact totals, or kahan_sum to reduce the rounding error of a floating-point sum.

Differences from Athena engine version 3

In Athena engine version 3, the sum of INTEGER or BIGINT values is a BIGINT. In DuckDB, it is a HUGEINT. To get a BIGINT, use CAST(sum(arg) AS BIGINT).

In Athena engine version 3, a query fails with an overflow error when a sum of BIGINT values does not fit in a BIGINT. In DuckDB, the query returns the sum as a HUGEINT.

weighted_avg function

Returns the weighted average of value: the sum of value * weight divided by the sum of the weights. Rows where value or weight is NULL are left out of both sums. If no row is left, the result is NULL.

weighted_avg is a macro. Before the query runs, the engine replaces the call with sum(value * weight) / sum(CASE WHEN value IS NOT NULL THEN weight ELSE 0 END). The wavg macro is a shorter name for the same calculation.

Syntax

weighted_avg(value, weight)

Arguments

The weighted_avg function takes the following arguments:

value

The numeric values to average.

weight

The numeric weight of each value. The weights do not have to add up to 1.

Return type

DOUBLE

Examples

The following SQL query compares the weighted average of three scores with their plain average.

SELECT weighted_avg(score, weight) AS weighted, avg(score) AS unweighted FROM (VALUES (90, 2), (80, 3), (70, 5) ) AS t(score, weight)

The query returns the following result.

weighted unweighted

77.0

80.0

The following SQL query has a NULL weight in the second row, so the function leaves that row out. The result is (90 * 2 + 70 * 5) / (2 + 5).

SELECT weighted_avg(score, weight) AS result FROM (VALUES (90, 2), (80, NULL), (70, 5) ) AS t(score, weight)

The query returns the following result.

result

75.71428571428571

The following SQL query has weights that add up to 0, so weighted_avg returns NaN, and isnan returns true.

SELECT isnan(weighted_avg(score, weight)) AS is_nan FROM (VALUES (90, 0), (80, 0)) AS t(score, weight)

The query returns the following result.

is_nan

true

Considerations

weighted_avg is a macro, not an aggregate function, so you cannot use it with OVER, FILTER, DISTINCT, or an ORDER BY clause inside the call. To weight only some rows, filter them with WHERE, or write the calculation yourself. For example, write sum(value * weight) FILTER (WHERE condition) / sum(weight) FILTER (WHERE condition AND value IS NOT NULL).

If the weights of the rows used add up to 0, the function divides by zero and returns NaN or Infinity, not NULL.

With integer inputs, value * weight is computed in the integer type, so a product that does not fit fails the query with an overflow error. To avoid this, cast value first, as in weighted_avg(CAST(value AS DOUBLE), weight).