Aggregate functions
AnalyticDB for PostgreSQL supports the aggregate functions of PostgreSQL 12. Aggregate functions perform calculations on a set of input rows and return a single result — for example, computing an average, a sum, or a maximum.
For the full PostgreSQL 12 specification, see Aggregate Functions.
Usage notes
All aggregate functions except
count()andcount(*)returnnull(not zero) when no input rows exist.array_agg()returnsnull(not an empty array) when no input rows exist. To replacenullwith a zero or an empty array, wrap the result withcoalesce().For
json_object_agg()andjsonb_object_agg(), key names cannot benull, but values can benull.For
array_agg()on an array type, all input arrays must have the same dimensionality and cannot be empty or null.Do not use types wrapped by
row()as input toarray_agg()on non-array types.
General-purpose aggregate functions
| Function | Input type | Return type | Description |
|---|---|---|---|
array_agg() | Any non-array type | Same as input | Concatenates input values, including null values, into an array. |
array_agg() | Any array type | Same as input | Concatenates input arrays into an array of one higher dimension. All inputs must have the same dimensionality and cannot be empty or null. |
avg() | SMALLINT, INT, BIGINT, REAL, DOUBLE PRECISION, NUMERIC, or INTERVAL | NUMERIC for integer input; DOUBLE PRECISION for floating-point input; same as input for other types | Returns the average of all non-null input values. |
bit_and() | SMALLINT, INT, BIGINT, or BIT | Same as input | Returns the bitwise AND of all non-null input values. Returns null if no non-null values exist. |
bit_or() | SMALLINT, INT, BIGINT, or BIT | Same as input | Returns the bitwise OR of all non-null input values. Returns null if no non-null values exist. |
bool_and() | BOOL | BOOL | Returns true if all input values are true; otherwise returns false. |
bool_or() | BOOL | BOOL | Returns true if at least one input value is true; otherwise returns false. |
count(*) | — | BIGINT | Returns the total number of input rows, including rows with null values. |
count() | Any | BIGINT | Returns the number of non-null input rows. |
every() | BOOL | BOOL | Equivalent to bool_and(). |
json_agg() | Any | JSON | Aggregates values, including null values, into a JSON array. |
jsonb_agg() | Any | JSONB | Aggregates values, including null values, into a JSONB array. |
json_object_agg(name, value) | (any, any) | JSON | Aggregates key-value pairs into a JSON object. Values can be null; keys cannot. |
jsonb_object_agg(name, value) | (any, any) | JSONB | Aggregates key-value pairs into a JSONB object. Values can be null; keys cannot. |
max() | Any array, numeric, string, date/time, network, or enumeration type, or array of these types | Same as input | Returns the maximum non-null value. |
min() | Any array, numeric, string, date/time, network, or enumeration type, or array of these types | Same as input | Returns the minimum non-null value. |
string_agg(expression, delimiter) | TEXT or BYTEA (both arguments) | Same as input | Concatenates non-null input values into a string, separated by the specified delimiter. |
sum() | SMALLINT, INT, BIGINT, REAL, DOUBLE PRECISION, NUMERIC, INTERVAL, or MONEY | BIGINT for SMALLINT or INT input; NUMERIC for BIGINT input; same as input for other types | Returns the sum of all non-null input values. |
xmlagg() | XML | XML | Concatenates non-null XML input values. |
Examples
The following examples use a sample orders table:
CREATE TABLE orders (
order_id INT,
customer_id INT,
amount DECIMAL(10, 2),
status TEXT
);
INSERT INTO orders VALUES
(1, 101, 250.00, 'completed'),
(2, 101, 80.50, 'completed'),
(3, 102, NULL, 'pending'),
(4, 103, 430.00, 'completed'),
(5, 102, 120.75, 'cancelled');Count rows and non-null values:
-- Total number of rows
SELECT count(*) FROM orders;
-- Result: 5
-- Number of rows where amount is not null
SELECT count(amount) FROM orders;
-- Result: 4Compute aggregates on non-null values:
SELECT
avg(amount) AS average_amount, -- ignores the NULL row
sum(amount) AS total_amount,
max(amount) AS max_amount,
min(amount) AS min_amount
FROM orders;
-- average_amount: 220.3125
-- total_amount: 881.25
-- max_amount: 430.00
-- min_amount: 80.50Group results and collect values into an array:
SELECT
customer_id,
array_agg(amount ORDER BY amount) AS amounts
FROM orders
WHERE amount IS NOT NULL
GROUP BY customer_id;
-- customer_id 101: {80.50, 250.00}
-- customer_id 103: {430.00}Concatenate values into a string:
SELECT string_agg(status, ', ' ORDER BY order_id) AS statuses
FROM orders;
-- Result: 'completed, completed, pending, completed, cancelled'Statistics-related aggregate functions
All functions in this section accept DOUBLE PRECISION input and return DOUBLE PRECISION (or BIGINT for regr_count).
| Function | Return type | Description |
|---|---|---|
corr(Y, X) | DOUBLE PRECISION | Returns the correlation coefficient between Y and X. |
covar_pop(Y, X) | DOUBLE PRECISION | Returns the population covariance between Y and X. |
covar_samp(Y, X) | DOUBLE PRECISION | Returns the sample covariance between Y and X. |
regr_avgx(Y, X) | DOUBLE PRECISION | Returns the average of the independent variable X: sum(X)/N, where N is the count of non-null X values. |
regr_avgy(Y, X) | DOUBLE PRECISION | Returns the average of the dependent variable Y: sum(Y)/N, where N is the count of non-null Y values. |
regr_count(Y, X) | BIGINT | Returns the number of rows where both Y and X are non-null. |
regr_intercept(Y, X) | DOUBLE PRECISION | Returns the y-intercept of the least-squares linear equation fitted from the (X, Y) data points. |
regr_r2(Y, X) | DOUBLE PRECISION | Returns the square of the correlation coefficient. |
regr_slope(Y, X) | DOUBLE PRECISION | Returns the slope of the least-squares linear equation fitted from the (X, Y) data points. |
regr_sxx(Y, X) | DOUBLE PRECISION | Returns the sum of squares of X: sum(X^2) - sum(X)^2/N. |
regr_sxy(Y, X) | DOUBLE PRECISION | Returns the sum of products of X and Y: sum(X*Y) - sum(X)*sum(Y)/N, where N is the count of non-null (Y, X) pairs. |
regr_syy(Y, X) | DOUBLE PRECISION | Returns the sum of squares of Y: sum(Y^2) - sum(Y)^2/N. |
stddev() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Alias of stddev_samp(). |
stddev_pop() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Returns the population standard deviation of the input values. |
stddev_samp() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Returns the sample standard deviation of the input values. |
variance() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Alias of var_samp(). |
var_pop() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Returns the population variance of the input values (the square of the population standard deviation). |
var_samp() | DOUBLE PRECISION for floating-point input; NUMERIC for other types | Returns the sample variance of the input values (the square of the sample standard deviation). |
Examples
The following examples use a sample measurements table with sensor readings:
CREATE TABLE measurements (
sensor_id INT,
reading DOUBLE PRECISION
);
INSERT INTO measurements VALUES
(1, 10.5),
(1, 12.3),
(1, NULL),
(2, 8.7),
(2, 9.1),
(2, 11.4);Compute standard deviation and variance per sensor:
SELECT
sensor_id,
stddev_samp(reading) AS sample_stddev,
stddev_pop(reading) AS pop_stddev,
var_samp(reading) AS sample_variance,
var_pop(reading) AS pop_variance
FROM measurements
GROUP BY sensor_id;Fit a simple linear regression between two columns:
SELECT
corr(reading, sensor_id) AS correlation,
regr_slope(reading, sensor_id) AS slope,
regr_intercept(reading, sensor_id) AS intercept,
regr_r2(reading, sensor_id) AS r_squared
FROM measurements;