PostgreSQL 18 reference · 12 entries

PostgreSQL Aggregate Functions

PostgreSQL aggregate functions: count(), sum(), avg(), min(), max(), string_agg(), array_agg(), bool_and(), percentile_cont(), mode() and the FILTER clause.

Aggregates turn the rows of each GROUP BY group into one value and ignore NULLs (except count(*)). Add ORDER BY inside the call to order collected values, and FILTER (WHERE …) to limit the rows one aggregate sees.

NameDescriptionSince
COUNT() Count rows: count(*) counts every row, count(x) skips NULLs, and count(DISTINCT x) counts unique values. Returns bigint.
SUM() Add up the non-NULL values in a group. Returns NULL, not 0, when there are no rows; wrap it in coalesce() if needed.
AVG() Return the average of the non-NULL values in a group. Integer input gives a numeric result with full precision.
MIN() Return the smallest value in a group. Works with numbers, text, dates and, since PostgreSQL 18, arrays.
MAX() Return the largest value in a group. Works with numbers, text, dates and, since PostgreSQL 18, arrays.
STRING_AGG() Join a group's non-NULL values into one string with a separator, optionally in a given ORDER BY order. 9.0
ARRAY_AGG() Collect a group's values, including NULLs, into an array, optionally in a given order.
BOOL_AND() Return true if every non-NULL value in a group is true. bool_or() returns true if at least one is.
PERCENTILE_CONT() Return the value at a percentile, interpolating between rows: percentile_cont(0.5) is the median. 9.4
MODE() Return the most frequent value in a group (the statistical mode). Ties go to the first value in sort order. 9.4
ANY_VALUE() Return an arbitrary non-NULL value from a group. Useful for columns you know are the same within each group. 16
FILTER Restrict which rows one aggregate sees with FILTER (WHERE …), so one query can count several conditions. 9.4

Was this page helpful?