Aggregate Functions
Aggregate functions take multiple values from documents, perform calculations, and return a single value as the result. The function names are case insensitive.
You can only use aggregate functions in SELECT
, LETTING
, HAVING
, and ORDER BY
clauses.
When using an aggregate function in a query, the query operates as an aggregate query.
In Couchbase Server 6.5 Enterprise Edition and later, aggregate functions can also be used as window functions, when they are used with a window definition, which is introduced by the OVER
keyword.
This page describes the syntax of aggregate functions. See the OVER clause and Window Functions page for the generic syntax of window functions, window options, and the window definition.
Syntax
Aggregate Functions as Window Functions
aggregatefunctionwindow ::= functionname '(' [ aggregatequantifier ] expr ')' OVER '(' windowdefinition ')'
Arguments
Aggregate functions take one argument, which is used to compute the aggregate function.
The COUNT
function can also take a wildcard (*) or a path with a wildcard (path.*) as its argument.
Aggregate Quantifier
aggregatequantifier ::= ALL  DISTINCT
The aggregate quantifier determines whether the function aggregates all values in the group, or distinct values only.
ALL

All objects are included in the computation.
DISTINCT

Only distinct objects are included in the computation.
This quantifier can only be used with aggregate functions.
This quantifier is optional.
If omitted, the default value is ALL
.
ARRAY_AGG( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns an array of the nonMISSING values in the group, including NULL values.
With the DISTINCT
quantifier, returns an array of the distinct nonMISSING values in the group, including NULL values.
Examples
List all values of the Cleanliness
reviews given.
SELECT ARRAY_AGG(reviews[0].ratings.Cleanliness) AS Reviews FROM `travelsample`;
[
{
"Reviews": [
1,
1,
1,
1,
1,
...
]
}
]
List all unique values of the Cleanliness
reviews given.
SELECT ARRAY_AGG(DISTINCT reviews[0].ratings.Cleanliness) AS Reviews FROM `travelsample`;
[
{
"UniqueReviews": [
1,
1,
2,
3,
4,
5
]
}
]
AVG( [ ALL  DISTINCT ] expression
)
This function has an alias MEAN().
Return Value
With the ALL
quantifier, or no quantifier, returns the arithmetic mean (average) of all the number values in the group.
With the DISTINCT
quantifier, returns the arithmetic mean (average) of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
Examples
The average altitude of airports in the travelsample
keyspace.
SELECT AVG(geo.alt) AS AverageAltitude FROM `travelsample` WHERE type="airport";
[
{
"AverageAltitude": 870.1651422764228
}
]
The average number of airline route stops vs. the DISTINCT
average of airline route stops.
SELECT AVG(stops) FROM `travelsample`; (1)
SELECT AVG(DISTINCT stops) FROM `travelsample`; (2)
1  Results in 0.0002 since nearly all docs have 0 stops. 
2  Results in 0.5 since the docs contain only 1 or 0 stops. 
COUNT( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns count of all the nonNULL and nonMISSING values in the group.
With the DISTINCT
quantifier, returns count of all the distinct nonNULL and nonMISSING values in the group.
Examples
The number of documents with an airline route stop in travelsample
regardless of its value.
SELECT COUNT(stops) AS CountOfStops FROM `travelsample`;
[
{
"CountOfStops": 24024
}
]
The number of unique values of airline route stops in travelsample
.
SELECT COUNT(DISTINCT stops) AS CountOfDistinctStops FROM `travelsample`;
[
{
"CountOfSDistinctStops": 2 (1)
}
]
1  Results in 2 because there are only 0 or 1 stops. 
COUNTN( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns a count of all the numeric values in the group.
With the DISTINCT
quantifier, returns a count of all the distinct numeric values in the group.
Examples
The count of numeric values in a mixed group.
SELECT COUNTN(list.val) AS CountOfNumbers
FROM [
{"val":1},
{"val":1},
{"val":2},
{"val":"abc"}
] AS list;
[
{
"CountOfNumbers": 3
}
]
The count of unique numeric values in a mixed group.
SELECT COUNTN(DISTINCT list.val) AS CountOfNumbers
FROM [
{"val":1},
{"val":1},
{"val":2},
{"val":"abc"}
] AS list;
[
{
"CountOfNumbers": 2
}
]
MAX( [ ALL  DISTINCT ] expression
)
Return Value
Returns the maximum nonNULL, nonMISSING value in the group in N1QL collation order.
This function returns the same result with the ALL
quantifier, the DISTINCT
quantifier, or no quantifier.
Examples
Max of an integer field.
Find the northernmost latitude of any hotel in travelsample
.
SELECT MAX(geo.lat) AS MaxLatitude FROM `travelsample` WHERE type="hotel";
[
{
"MaxLatitude": 60.15356
}
]
Max of a string field.
Find the hotel whose name is last alphabetically in travelsample
.
SELECT MAX(name) AS MaxName FROM `travelsample` WHERE type="hotel";
[
{
"MaxName": "pentahotel Birmingham"
}
]
That result might have been surprising since lowercase letters come after uppercase letters and are therefore "higher" than uppercase letters. To avoid this uppercase/lowercase confusion, you should first make all values uppercase or lowercase, as in the following example.
Max of a string field, regardless of case.
Find the hotel whose name is last alphabetically in travelsample
.
SELECT MAX(UPPER(name)) AS MaxName FROM `travelsample` WHERE type="hotel";
[
{
"MaxName": "YOSEMITE LODGE AT THE FALLS"
}
]
MEAN( [ ALL  DISTINCT ] expression
)
Alias for AVG().
MEDIAN( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns the median of all the number values in the group.
If there is an even number of number values, returns the mean of the median two values.
With the DISTINCT
quantifier, returns the median of all the distinct number values in the group.
If there is an even number of distinct number values, returns the mean of the median two values.
Returns NULL if there are no number values in the group.
Examples
The median altitude of airports in the travelsample
keyspace.
SELECT MEDIAN(geo.alt) AS MedianAltitude FROM `travelsample` WHERE type="airport";
[
{
"MedianAltitude": 361.5
}
]
The median of distinct altitudes of airports in the travelsample
keyspace.
SELECT MEDIAN(DISTINCT geo.alt) AS MedianDistinctAltitude FROM `travelsample` WHERE type="airport";
[
{
"MedianDistinctAltitude": 758
}
]
MIN( [ ALL  DISTINCT ] expression
)
Return Value
Returns the minimum nonNULL, nonMISSING value in the group in N1QL collation order.
This function returns the same result with the ALL
quantifier, the DISTINCT
quantifier, or no quantifier.
Examples
Min of an integer field.
Find the southernmost latitude of any hotel in travelsample
.
SELECT MIN(geo.lat) AS MinLatitude FROM `travelsample` WHERE type="hotel";
[
{
"MinLatitude": 32.68092
}
]
Min of a string field.
Find the hotel whose name is first alphabetically in travelsample
.
SELECT MIN(name) AS MinName FROM `travelsample` WHERE type="hotel";
[
{
"MinName": "'La Mirande Hotel"
}
]
That result might have been surprising since some symbols come before letters and are therefore "lower" than letters. To avoid this symbol confusion, you can specify letters only, as in the following example.
Min of a string field, regardless of preceding nonletters.
Find the first hotel alphabetically in travelsample
.
SELECT MIN(name) AS MinName FROM `travelsample` WHERE type="hotel" AND SUBSTR(name,0)>="A";
[
{
"MinName": "AIRE NATURELLE LE GROZEAU Aire naturelle"
}
]
STDDEV( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns the corrected sample standard deviation of all the number values in the group.
With the DISTINCT
quantifier, returns the corrected sample standard deviation of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
Examples
Sample standard deviation of all values.
SELECT STDDEV(reviews[0].ratings.Cleanliness) AS StdDev FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"StdDev": 2.0554275433769753
}
]
Sample standard deviation of a single value.
SELECT STDDEV(reviews[0].ratings.Cleanliness) AS StdDevSingle FROM `travelsample` WHERE name="Sachas Hotel";
[
{
"StdDevSingle": 0 (1)
}
]
1  There is only one matching result in the input, so the function returns 0 . 
Sample standard deviation of distinct values.
SELECT STDDEV(DISTINCT reviews[0].ratings.Cleanliness) AS StdDevDistinct FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"StdDevDistinct": 2.1602468994692865
}
]
STDDEV_POP( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns the population standard deviation of all the number values in the group.
With the DISTINCT
quantifier, returns the population standard deviation of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
Examples
Population standard deviation of all values.
SELECT STDDEV_POP(reviews[0].ratings.Cleanliness) AS PopStdDev FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"PopStdDev": 2.0390493736539432
}
]
Population standard deviation of distinct values.
SELECT STDDEV_POP(DISTINCT reviews[0].ratings.Cleanliness) AS PopStdDevDistinct FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"PopStdDevDistinct": 1.9720265943665387
}
]
STDDEV_SAMP( [ ALL  DISTINCT ] expression
)
A nearsynonym for STDDEV().
The only difference is that STDDEV_SAMP()
returns NULL if there is only one matching element.
SUM( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns the sum of all the number values in the group.
With the DISTINCT
quantifier, returns the arithmetic sum of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
Examples
The sum total of all airline route stops in travelsample
.
In the travelsample bucket, nearly all flights are nonstop (0 stops) and only six flights have 1 stop, so we expect 6 flights of 1 stop each, a total of 6. 
SELECT SUM(stops) AS SumOfStops FROM `travelsample`;
[
{
"SumOfStops": 6 (1)
}
]
1  There are 6 routes with 1 stop each. 
The sum total of all unique numbers of airline route stops in travelsample
.
SELECT SUM(DISTINCT stops) AS SumOfDistinctStops FROM `travelsample`;
[
{
"SumOfDistinctStops": 1 (1)
}
]
1  There are only 0 and 1 stops per route; and 0 + 1 = 1. 
VARIANCE( [ ALL  DISTINCT ] expression
)
Return Value
With the ALL
quantifier, or no quantifier, returns the unbiased sample variance (the square of the corrected sample standard deviation) of all the number values in the group.
With the DISTINCT
quantifier, returns the unbiased sample variance (the square of the corrected sample standard deviation) of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
This function has a nearsynonym VARIANCE_SAMP().
The only difference is that VARIANCE()
returns NULL if there is only one matching element.
Examples
Sample variance of all values.
SELECT VARIANCE(reviews[0].ratings.Cleanliness) AS Variance FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"Variance": 4.224782386072708
}
]
Sample variance of a single value.
SELECT VARIANCE(reviews[0].ratings.Cleanliness) AS VarianceSingle FROM `travelsample` WHERE name="Sachas Hotel";
[
{
"VarianceSingle": 0 (1)
}
]
1  There is only one matching result in the input, so the function returns 0 . 
Sampling variance of distinct values.
SELECT VARIANCE(DISTINCT reviews[0].ratings.Cleanliness) AS VarianceDistinct FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"VarianceDistinct": 4.666666666666667
}
]
VARIANCE_POP( [ ALL  DISTINCT ] expression
)
This function has an alias VAR_POP().
Return Value
With the ALL
quantifier, or no quantifier, returns the population variance (the square of the population standard deviation) of all the number values in the group.
With the DISTINCT
quantifier, returns the population variance (the square of the population standard deviation) of all the distinct number values in the group.
Returns NULL if there are no number values in the group.
Examples
Population variance of all values.
SELECT VARIANCE_POP(reviews[0].ratings.Cleanliness) AS PopVariance FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"PopVariance": 4.157722348198537
}
]
Population variance of distinct values.
SELECT VARIANCE_POP(DISTINCT reviews[0].ratings.Cleanliness) AS PopVarianceDistinct FROM `travelsample` WHERE city="London" AND `type`="hotel";
[
{
"PopVarianceDistinct": 3.8888888888888893
}
]
VARIANCE_SAMP( [ ALL  DISTINCT ] expression
)
A nearsynonym for VARIANCE().
The only difference is that VARIANCE_SAMP()
returns NULL if there is only one matching element.
This function has an alias VAR_SAMP().
VAR_POP( [ ALL  DISTINCT ] expression
)
Alias for VARIANCE_POP().
VAR_SAMP( [ ALL  DISTINCT ] expression
)
Alias for VARIANCE_SAMP().
Formulas
The corrected sample standard deviation is calculated according to the following formula.
The population standard deviation is calculated according to the following formula.
Related Links
GROUP BY Clause for GROUP BY, LETTING, and HAVING clauses.