View a markdown version of this page

General aggregate functions - Amazon Athena

General aggregate functions

Use these functions for common aggregations, such as counting rows, finding the smallest or largest value, and collecting the values of a group into a list or a string. This page also describes the DISTINCT, ORDER BY, and FILTER clauses, which change the input rows of an aggregate function call or their order.

For a description of the sample tables that the examples on this page use, see SELECT statement in DuckDB.

Aggregate function clauses

An aggregate function call can include clauses that change which input rows the function reads and the order in which it reads them. Each clause applies only to the call that it belongs to, so other aggregates in the same select list still read every row.

DISTINCT removes duplicate values before the function reads them, so count(DISTINCT region) counts each region once. ORDER BY inside the parentheses sets the order of the input rows for that call. It changes the result only of functions that depend on input order, such as any_value, first, list, and string_agg. Without it, the query does not define that order. FILTER (WHERE condition) after the call passes only the rows for which condition is true.

Syntax

aggregate_function ( [ DISTINCT ] expression [, ...] [ ORDER BY sort_expression [ ASC | DESC ] [ NULLS { FIRST | LAST } ] [, ...] ] ) [ FILTER ( WHERE condition ) ]

Examples

The following SQL query counts all orders. In the same query, it uses FILTER to count only the orders over 50 and to total only the orders in the east region. The sum function skips the NULL amount for frank.

SELECT count(*) AS all_orders, count(*) FILTER ( WHERE amount > 50 ) AS large_orders, sum(amount) FILTER ( WHERE region = 'east' ) AS east_total FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount)

The query returns the following result.

all_orders large_orders east_total

6

3

162.75

The following SQL query uses ORDER BY inside string_agg to list the customers from the largest order to the smallest. The row whose amount is NULL sorts last.

SELECT string_agg( customer, ', ' ORDER BY amount DESC ) AS customers_by_amount FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount)

The query returns the following result.

customers_by_amount

dave, alice, bob, carol, erin, frank

The following SQL query compares count with and without DISTINCT. Six rows have a region, and there are three distinct regions.

SELECT count(region) AS region_values, count(DISTINCT region) AS distinct_regions FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount)

The query returns the following result.

region_values distinct_regions

6

3

The following SQL query has no rows that pass the WHERE clause. count returns 0, sum returns NULL, and coalesce turns that NULL into zero.

SELECT count(*) AS order_count, sum(amount) AS total, coalesce(sum(amount), 0) AS total_or_zero FROM (VALUES (1, 'alice', 'east', 120.50), (2, 'bob', 'west', 75.00), (3, 'carol', 'east', 42.25), (4, 'dave', 'north', 310.00), (5, 'erin', 'west', 18.75), (6, 'frank', 'east', NULL) ) AS sales(order_id, customer, region, amount) WHERE amount > 1000

The query returns the following result.

order_count total total_or_zero

0

NULL

0.00

Considerations

If no input rows reach an aggregate, for example because WHERE or FILTER removes them all, count returns 0 and most other aggregate functions, such as sum, return NULL. To show 0 instead, wrap the call in coalesce, as in coalesce(sum(amount), 0).

approx_count_distinct function

Returns an estimate of the number of distinct non-NULL values of value, computed with the HyperLogLog algorithm. The result is an estimate, so it can be lower or higher than the exact number of distinct values. For an exact count, use count(DISTINCT value).

NULL values are not counted. If every value is NULL, or if there are no input rows, the result is 0, not NULL.

Syntax

approx_count_distinct(value)

Arguments

The approx_count_distinct function takes the following argument:

value

The expression whose distinct values the function counts. It can be of any type.

Return type

BIGINT

Examples

The following SQL query estimates the number of distinct values. The duplicate 1 is counted once, and the NULL is not counted.

SELECT approx_count_distinct(x) AS result FROM (VALUES (1), (1), (2), (NULL), (3)) AS v(x)

The query returns the following result.

result

3

The following SQL query compares the estimate with the exact count for the 1,000 distinct integers from 0 to 999. The estimate is close to the exact count, but not equal to it.

SELECT approx_count_distinct(x) AS approx_result, count(DISTINCT x) AS exact_result FROM range(1000) AS t(x)

The query returns the following result.

approx_result exact_result

978

1000

The following SQL query passes only NULL values. The result is 0, not NULL.

SELECT approx_count_distinct(x) AS result FROM (VALUES (CAST(NULL AS INTEGER)), (NULL)) AS v(x)

The query returns the following result.

result

0

Considerations

Do not use the estimate where you need an exact answer, such as to check that a key column has no duplicates. Use count(DISTINCT value) for that.

approx_count_distinct takes one argument. You cannot pass an error bound to it.

Differences from Athena engine version 3

Athena engine version 3 names this function approx_distinct, and DuckDB has no approx_distinct function. Replace approx_distinct(x) with approx_count_distinct(x). The two engines use different estimators, so on large inputs the estimates can differ.

In Athena engine version 3, approx_distinct also takes an optional second argument, the maximum standard error of the estimate. The approx_count_distinct function takes only the value to count, so remove that argument when you port a query.

count function

Returns how many rows a group has, or how many of its values are not NULL. Both count(*) and count() count every row, including rows whose values are all NULL. A call to count(expression) counts only the rows where expression is not NULL. With DISTINCT, it counts each distinct value that is not NULL once.

count never returns NULL. For empty input, or when every value of expression is NULL, the result is 0.

count_star() returns the same result as count(*).

Syntax

count(*) count() count([ DISTINCT ] expression) count_star()

Arguments

The count function takes the following argument:

expression

The values to count, of any type. Rows where expression is NULL are not counted.

Return type

BIGINT

Examples

The following SQL query counts all rows, the values that are not NULL, and the distinct values.

SELECT count(*) AS all_rows, count(x) AS non_null_values, count(DISTINCT x) AS distinct_values FROM (VALUES (1), (NULL), (3), (3)) AS v(x)

The query returns the following result.

all_rows non_null_values distinct_values

4

3

2

The following SQL query counts per group. Group b has only a NULL value, so its count is 0, not NULL.

SELECT g, count(x) AS result FROM (VALUES ('a', 1), ('a', NULL), ('b', NULL) ) AS v(g, x) GROUP BY g ORDER BY g

The query returns the following results.

g result

a

1

b

0

The following SQL query counts the distinct pairs of x and y. The pair (1, NULL) is counted, because a STRUCT value with a NULL field is not itself NULL.

SELECT count(DISTINCT (x, y)) AS distinct_pairs FROM (VALUES (1, 2), (1, 2), (1, NULL)) AS v(x, y)

The query returns the following result.

distinct_pairs

2

The following SQL query uses count_star(), which counts every row, including the row with a NULL value.

SELECT count_star() AS result FROM (VALUES (1), (NULL), (3)) AS v(x)

The query returns the following result.

result

3

Considerations

count takes at most one argument, so a call such as count(DISTINCT x, y) fails. To count distinct combinations of several columns, combine the columns into one STRUCT value with a row constructor, as in count(DISTINCT (x, y)). A STRUCT value is NULL only when the value itself is NULL, not when its fields are, so a combination whose fields are all NULL is counted too.

count_if function

Returns the number of input rows for which condition is true. Rows where condition is false or NULL are not counted.

If there are no input rows, or if condition is NULL for every row, the result is NULL, not 0. To get 0 in those cases, use coalesce(count_if(condition), 0), or use count(*) FILTER (WHERE condition), which returns a BIGINT.

countif is an alias of count_if.

Syntax

count_if(condition)

Arguments

The count_if function takes the following argument:

condition

The condition to test for each row, as a BOOLEAN expression. A value of another data type, such as an INTEGER, makes the query fail.

Return type

HUGEINT

Examples

The following SQL query counts the true values in a column.

SELECT count_if(a) AS result FROM (VALUES (true), (false), (true)) AS t(a)

The query returns the following result.

result

2

The following SQL query uses the countif alias to count the orders over 100 in each region. The west region has no such orders, so its count is 0.

SELECT region, countif(amount > 100) AS large_orders FROM (VALUES ('east', 120.5), ('west', 75.0), ('east', 42.25), ('north', 310.0), ('west', 18.75) ) AS t(region, amount) GROUP BY region ORDER BY region

The query returns the following results.

region large_orders

east

1

north

1

west

0

The following SQL query has no input rows, because the WHERE clause removes them all. count_if returns NULL, and the coalesce form and the FILTER form both return 0.

SELECT count_if(amount > 100) AS count_if_result, coalesce( count_if(amount > 100), 0 ) AS with_coalesce, count(*) FILTER (WHERE amount > 100) AS with_filter FROM (VALUES (120.5), (75.0)) AS t(amount) WHERE amount < 0

The query returns the following result.

count_if_result with_coalesce with_filter

NULL

0

0

The following SQL query counts a column whose values are all NULL, so the result is NULL.

SELECT count_if(flag) AS result FROM (VALUES (CAST(NULL AS BOOLEAN)), (CAST(NULL AS BOOLEAN)) ) AS t(flag)

The query returns the following result.

result

NULL

Considerations

Hive tables cannot store HUGEINT values. To write the result to a Hive table, cast it, for example CAST(count_if(condition) AS BIGINT).

Differences from Athena engine version 3

In Athena engine version 3, count_if returns a BIGINT. In DuckDB, it returns a HUGEINT.

In Athena engine version 3, count_if returns 0 when there are no input rows or when condition is NULL for every row. In DuckDB, it returns NULL in those cases. To get the Athena engine version 3 result, use coalesce(count_if(condition), 0).

list function

Returns a LIST that holds the value of arg from every row in the group, including NULL values. To set the order of the elements, add ORDER BY inside the call. Without ORDER BY, the order of the elements is not guaranteed. To keep one copy of each value, add DISTINCT.

If the group has no rows, the result is NULL, not an empty list. array_agg is an alias of list.

Syntax

list([ DISTINCT ] arg [ ORDER BY sort_expression [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] [, ...] ]) [ FILTER (WHERE condition) ] array_agg([ DISTINCT ] arg [ ORDER BY sort_expression [ ASC | DESC ] [ NULLS FIRST | NULLS LAST ] [, ...] ]) [ FILTER (WHERE condition) ]

Arguments

The list function takes the following arguments:

arg

The value to collect, of any type.

sort_expression

An expression that sets the order of the elements in the result. NULL values of sort_expression sort last unless you add NULLS FIRST. This argument is optional.

condition

The condition that selects the rows to collect, as a BOOLEAN expression. The function collects only the rows where condition is true. This argument is optional.

Return type

A LIST of the type of arg, for example INTEGER[] when arg is an INTEGER.

Examples

The following SQL query collects three values into a list in ascending order.

SELECT list(x ORDER BY x) AS result FROM (VALUES (3), (1), (2)) AS v(x)

The query returns the following result.

result

[1, 2, 3]

The following SQL query uses the array_agg alias. array_agg keeps the NULL value and sorts it last. With FILTER, it leaves the NULL value out.

SELECT array_agg(x ORDER BY x) AS with_nulls, array_agg( x ORDER BY x ) FILTER (WHERE x IS NOT NULL) AS without_nulls FROM (VALUES (3), (NULL), (1)) AS v(x)

The query returns the following result.

with_nulls without_nulls

[1, 3, NULL]

[1, 3]

The following SQL query lists the customers in each region of a table, in order of their order IDs.

SELECT region, list(customer ORDER BY order_id) AS customers FROM sales_db.sales_parquet GROUP BY region ORDER BY region

The query returns the following results.

region customers

east

[alice, carol, frank]

north

[dave]

west

[bob, erin]

The following SQL query uses WHERE to filter out every row, so list has nothing to collect and returns NULL. Use coalesce to return an empty list instead.

SELECT list(x) IS NULL AS is_null, coalesce(list(x), []) AS empty_list FROM (VALUES (1), (2)) AS v(x) WHERE x > 5

The query returns the following result.

is_null empty_list

true

[]

lttb function

Selects up to n of the (x, y) points in a group and returns them as a LIST of STRUCT values with the fields x and y. Use it to shrink a long time series before you chart it. To choose the points, the function uses the Largest Triangle Three Buckets (LTTB) algorithm. The algorithm keeps the points that best preserve the shape of the series, such as peaks, and always keeps the first and the last point.

The function reads the points in the order that they reach it, so always add ORDER BY x inside the call. Rows where x or y is NULL are skipped. If the group has n points or fewer, the function returns all of them. If the group has no rows, the result is NULL.

Syntax

lttb(x, y, n ORDER BY x)

Arguments

The lttb function takes the following arguments:

x

The position of each point along the series, such as a time. A DOUBLE, FLOAT, TIMESTAMP, or TIMESTAMP WITH TIME ZONE value, or another timestamp type. Integer and DECIMAL values are converted to DOUBLE.

y

The value of each point, as a DOUBLE or FLOAT value. Integer and DECIMAL values are converted to DOUBLE.

n

The largest number of points to return, as a constant BIGINT. It must be at least 2.

Return type

A LIST of STRUCT(x, y) values. The field x is a DOUBLE, a FLOAT, or the timestamp type of x, and the field y is a DOUBLE or a FLOAT. Integer and DECIMAL inputs give DOUBLE fields. For example, the result is STRUCT(x DOUBLE, y DOUBLE)[] for DECIMAL input and STRUCT(x TIMESTAMP, y DOUBLE)[] for a TIMESTAMP series.

Examples

The following SQL query reduces four points to two. The result keeps the first and the last point.

SELECT lttb(x, y, 2 ORDER BY x) AS result FROM (VALUES (1.0, 2.0), (2.0, 3.5), (3.0, 7.0), (4.0, 8.5) ) AS v(x, y)

The query returns the following result.

result

[{'x': 1.0, 'y': 2.0}, {'x': 4.0, 'y': 8.5}]

The following SQL query reduces six hourly readings to three and uses unnest to return one row for each point. The result keeps the spike at 02:00 as well as the first and the last reading.

SELECT point.x AS reading_time, point.y AS reading FROM ( SELECT unnest( lttb(ts, reading, 3 ORDER BY ts) ) AS point FROM (VALUES (TIMESTAMP '2026-10-01 00:00:00', 2.0), (TIMESTAMP '2026-10-01 01:00:00', 2.5), (TIMESTAMP '2026-10-01 02:00:00', 9.0), (TIMESTAMP '2026-10-01 03:00:00', 3.0), (TIMESTAMP '2026-10-01 04:00:00', 2.8), (TIMESTAMP '2026-10-01 05:00:00', 3.1) ) AS v(ts, reading) ) AS s ORDER BY reading_time

The query returns the following results.

reading_time reading

2026-10-01 00:00:00

2.0

2026-10-01 02:00:00

9.0

2026-10-01 05:00:00

3.1

Considerations

If n is not a constant, or is less than 2, the query fails.

The fields of each result point are always named x and y, whatever the names of the input columns. To get one row for each point, pass the result to unnest.

max function

Returns the largest value of arg in the group. With n, returns a LIST of the n largest values, from largest to smallest. A value that occurs more than once can fill more than one place in that list. To count each value once, use max(DISTINCT arg, n).

NULL values are ignored. If the group has no values that are not NULL, the result is NULL. max works on any type that can be ordered, including strings, dates, lists, and structs. To return a value from the row that has the largest value, use arg_max. To find the smallest values, use the min function.

Syntax

max(arg) max(arg, n)

Arguments

The max function takes the following arguments:

arg

The values to compare, of any type that can be ordered.

n

The number of values to return, as a BIGINT greater than 0.

Return type

The type of arg. With n, a LIST of the type of arg.

Examples

The following SQL query returns the largest value. The NULL value is ignored.

SELECT max(x) AS result FROM (VALUES (3), (7), (NULL), (5)) AS v(x)

The query returns the following result.

result

7

The following SQL query returns the two largest values as a list.

SELECT max(x, 2) AS result FROM (VALUES (3), (7), (1), (5)) AS v(x)

The query returns the following result.

result

[7, 5]

The following SQL query returns the largest order amount in each region of a table.

SELECT region, max(amount) AS max_amount FROM sales_db.sales_parquet GROUP BY region ORDER BY region

The query returns the following results.

region max_amount

east

120.50

north

310.00

west

75.00

The following SQL query shows that max returns NaN when an input value is NaN, and that FILTER leaves the NaN value out.

SELECT isnan(max(x)) AS max_is_nan, max(x) FILTER ( WHERE NOT isnan(x) ) AS max_without_nan FROM (VALUES (1.5E0), (CAST('NaN' AS DOUBLE))) AS v(x)

The query returns the following result.

max_is_nan max_without_nan

true

1.5

Considerations

NaN is larger than every other DOUBLE or FLOAT value, so max returns NaN when any input value is NaN. To ignore NaN values, add FILTER (WHERE NOT isnan(arg)).

If n is 0 or negative, the query fails.

Differences from Athena engine version 3

In Athena engine version 3, max ignores NaN values when the group also has other values. In DuckDB, NaN is the largest value, so max returns NaN. To ignore NaN values, use max(arg) FILTER (WHERE NOT isnan(arg)).

min function

Returns the smallest value of arg in the group. With n, returns a LIST of the n smallest values, from smallest to largest. A value that occurs more than once can fill more than one place in that list. To count each value once, use min(DISTINCT arg, n).

NULL values are ignored. If the group has no values that are not NULL, the result is NULL. min works on any type that can be ordered, including strings, dates, lists, and structs. To return a value from the row that has the smallest value, use arg_min. To find the largest values, use the max function.

Syntax

min(arg) min(arg, n)

Arguments

The min function takes the following arguments:

arg

The values to compare, of any type that can be ordered.

n

The number of values to return, as a BIGINT greater than 0.

Return type

The type of arg. With n, a LIST of the type of arg.

Examples

The following SQL query returns the smallest value. The NULL value is ignored.

SELECT min(x) AS result FROM (VALUES (3), (7), (NULL), (5)) AS v(x)

The query returns the following result.

result

3

The following SQL query returns the two smallest values as a list.

SELECT min(x, 2) AS result FROM (VALUES (3), (7), (1), (5)) AS v(x)

The query returns the following result.

result

[1, 3]

The following SQL query returns the smallest and the largest of three strings. Banana is the smallest value because uppercase letters sort before lowercase letters, and cherry is the largest.

SELECT min(s) AS min_value, max(s) AS max_value FROM (VALUES ('apple'), ('Banana'), ('cherry')) AS v(s)

The query returns the following result.

min_value max_value

Banana

cherry

The following SQL query returns the earliest and the latest order date in a table.

SELECT min(order_date) AS earliest, max(order_date) AS latest FROM sales_db.sales_parquet

The query returns the following result.

earliest latest

2026-10-01

2026-10-04

Considerations

Strings compare by character code, so every uppercase ASCII letter sorts before every lowercase letter.

NaN is larger than every other DOUBLE or FLOAT value, so min returns NaN only when every value in the group is NaN.

If n is 0 or negative, the query fails.

string_agg function

Converts each value that is not NULL to VARCHAR and joins the results into one string, with separator between each value and the next. If you omit separator, the function uses a comma (,) with no space after it. If every value is NULL, or the group has no rows, the result is NULL, not an empty string.

Without an ORDER BY clause in the call, the order of the values in the result is not guaranteed. Write the ORDER BY clause inside the parentheses, after the last argument, for example string_agg(name, ', ' ORDER BY name). Add DISTINCT before value to join each distinct value only once.

group_concat and listagg are aliases of string_agg.

Syntax

string_agg([ DISTINCT ] value [, separator ] [ ORDER BY sort_expression [ ASC | DESC ] [, ...] ])

Arguments

The string_agg function takes the following arguments:

value

The values to join. Values of any type are converted to VARCHAR.

separator

The text to put between the values, as a constant VARCHAR value. The default is ','. This argument is optional.

sort_expression

An expression that sets the order of the values in the result. It does not have to be value, except with DISTINCT: then it must be value, or the query fails. This argument is optional.

Return type

VARCHAR

Examples

The following SQL query joins three strings with a hyphen, in alphabetical order.

SELECT string_agg(x, '-' ORDER BY x) AS result FROM (VALUES ('a'), ('b'), ('c')) AS t(x)

The query returns the following result.

result

a-b-c

The following SQL query orders the values by another column, from the largest quantity to the smallest.

SELECT string_agg(name, ', ' ORDER BY qty DESC) AS result FROM (VALUES ('apple', 3), ('pear', 1), ('fig', 2) ) AS t(name, qty)

The query returns the following result.

result

apple, fig, pear

The following SQL query uses the default separator and skips NULL values. Group 2 has only a NULL, so its result is NULL.

SELECT g, string_agg(x ORDER BY x) AS result FROM (VALUES (1, 'b'), (1, NULL), (1, 'a'), (2, NULL) ) AS t(g, x) GROUP BY g ORDER BY g

The query returns the following results.

g result

1

a,b

2

NULL

The following SQL query uses the listagg alias, with the ORDER BY clause inside the parentheses.

SELECT listagg(x, ' | ' ORDER BY x) AS result FROM (VALUES ('east'), ('west'), ('north')) AS t(x)

The query returns the following result.

result

east | north | west

Considerations

separator must be a constant. The query fails if you pass a column. If separator is NULL, the result is NULL.

To get an empty string instead of NULL for a group with no values, use coalesce(string_agg(value, separator), '').

Differences from Athena engine version 3

Athena engine version 3 uses the form listagg(value, separator) WITHIN GROUP (ORDER BY sort_expression). DuckDB does not support WITHIN GROUP for listagg, string_agg, or group_concat, so a query that uses it fails. Write string_agg(value, separator ORDER BY sort_expression) instead.