ℹ️ Skipped - page is already crawled
| Filter | Status | Condition | Details |
|---|---|---|---|
| HTTP status | PASS | download_http_code = 200 | HTTP 200 |
| Age cutoff | PASS | download_stamp > now() - 6 MONTH | 0.1 months ago |
| History drop | PASS | isNull(history_drop_reason) | No drop reason |
| Spam/ban | PASS | fh_dont_index != 1 AND ml_spam_score = 0 | ml_spam_score=0 |
| Canonical | PASS | meta_canonical IS NULL OR = '' OR = src_unparsed | Not set |
| Property | Value |
|---|---|
| URL | https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators |
| Last Crawled | 2026-04-04 08:19:26 (2 days ago) |
| First Indexed | 2025-02-21 00:56:27 (1 year ago) |
| HTTP Status Code | 200 |
| Meta Title | Aggregate Function Combinators | ClickHouse Docs |
| Meta Description | Documentation for Aggregate Function Combinators |
| Meta Canonical | null |
| Boilerpipe Text | The name of an aggregate function can have a suffix appended to it. This changes the way the aggregate function works.
-If
The suffix -If can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument – a condition (Uint8 type). The aggregate function processes only the rows that trigger the condition. If the condition was not triggered even once, it returns a default value (usually zeros or empty strings).
Examples:
sumIf(column, cond)
,
countIf(cond)
,
avgIf(x, cond)
,
quantilesTimingIf(level1, level2)(x, cond)
,
argMinIf(arg, val, cond)
and so on.
With conditional aggregate functions, you can calculate aggregates for several conditions at once, without using subqueries and
JOIN
s. For example, conditional aggregate functions can be used to implement the segment comparison functionality.
-Array
The -Array suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. When processing arrays, the aggregate function works like the original aggregate function across all array elements.
Example 1:
sumArray(arr)
- Totals all the elements of all 'arr' arrays. In this example, it could have been written more simply:
sum(arraySum(arr))
.
Example 2:
uniqArray(arr)
– Counts the number of unique elements in all 'arr' arrays. This could be done an easier way:
uniq(arrayJoin(arr))
, but it's not always possible to add 'arrayJoin' to a query.
-If and -Array can be combined. However, 'Array' must come first, then 'If'. Examples:
uniqArrayIf(arr, cond)
,
quantilesTimingArrayIf(level1, level2)(arr, cond)
. Due to this order, the 'cond' argument won't be an array.
-Map
The -Map suffix can be appended to any aggregate function. This will create an aggregate function which gets Map type as an argument, and aggregates values of each key of the map separately using the specified aggregate function. The result is also of a Map type.
Example
CREATE
TABLE
map_map
(
date
Date
,
timeslot
DateTime
,
status
Map
(
String
,
UInt64
)
)
ENGINE
=
MergeTree
ORDER
BY
(
)
;
INSERT
INTO
map_map
VALUES
(
'2000-01-01'
,
'2000-01-01 00:00:00'
,
(
[
'a'
,
'b'
,
'c'
]
,
[
10
,
10
,
10
]
)
)
,
(
'2000-01-01'
,
'2000-01-01 00:00:00'
,
(
[
'c'
,
'd'
,
'e'
]
,
[
10
,
10
,
10
]
)
)
,
(
'2000-01-01'
,
'2000-01-01 00:01:00'
,
(
[
'd'
,
'e'
,
'f'
]
,
[
10
,
10
,
10
]
)
)
,
(
'2000-01-01'
,
'2000-01-01 00:01:00'
,
(
[
'f'
,
'g'
,
'g'
]
,
[
10
,
10
,
10
]
)
)
;
SELECT
timeslot
,
sumMap
(
status
)
,
avgMap
(
status
)
,
minMap
(
status
)
FROM
map_map
GROUP
BY
timeslot
;
┌────────────timeslot─┬─sumMap
(
status
)
───────────────────────┬─avgMap
(
status
)
───────────────────────┬─minMap
(
status
)
───────────────────────┐
│
2000
-
01
-
01
00
:
00
:
00
│ {
'a'
:
10
,
'b'
:
10
,
'c'
:
20
,
'd'
:
10
,
'e'
:
10
} │ {
'a'
:
10
,
'b'
:
10
,
'c'
:
10
,
'd'
:
10
,
'e'
:
10
} │ {
'a'
:
10
,
'b'
:
10
,
'c'
:
10
,
'd'
:
10
,
'e'
:
10
} │
│
2000
-
01
-
01
00
:
01
:
00
│ {
'd'
:
10
,
'e'
:
10
,
'f'
:
20
,
'g'
:
20
} │ {
'd'
:
10
,
'e'
:
10
,
'f'
:
10
,
'g'
:
10
} │ {
'd'
:
10
,
'e'
:
10
,
'f'
:
10
,
'g'
:
10
} │
└─────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┘
-SimpleState
If you apply this combinator, the aggregate function returns the same value but with a different type. This is a
SimpleAggregateFunction(...)
that can be stored in a table to work with
AggregatingMergeTree
tables.
Syntax
<
aggFunction
>
SimpleState
(
x
)
Arguments
x
— Aggregate function parameters.
Returned values
The value of an aggregate function with the
SimpleAggregateFunction(...)
type.
Example
Query:
WITH
anySimpleState
(
number
)
AS
c
SELECT
toTypeName
(
c
)
,
c
FROM
numbers
(
1
)
;
Result:
┌─toTypeName(c)────────────────────────┬─c─┐
│ SimpleAggregateFunction(any, UInt64) │ 0 │
└──────────────────────────────────────┴───┘
-State
If you apply this combinator, the aggregate function does not return the resulting value (such as the number of unique values for the
uniq
function), but an intermediate state of the aggregation (for
uniq
, this is the hash table for calculating the number of unique values). This is an
AggregateFunction(...)
that can be used for further processing or stored in a table to finish aggregating later.
Note
Please notice, that -MapState is not an invariant for the same data due to the fact that order of data in intermediate state can change, though it doesn't impact ingestion of this data.
To work with these states, use:
AggregatingMergeTree
table engine.
finalizeAggregation
function.
runningAccumulate
function.
-Merge
combinator.
-MergeState
combinator.
-Merge
If you apply this combinator, the aggregate function takes the intermediate aggregation state as an argument, combines the states to finish aggregation, and returns the resulting value.
-MergeState
Merges the intermediate aggregation states in the same way as the -Merge combinator. However, it does not return the resulting value, but an intermediate aggregation state, similar to the -State combinator.
-ForEach
Converts an aggregate function for tables into an aggregate function for arrays that aggregates the corresponding array items and returns an array of results. For example,
sumForEach
for the arrays
[1, 2]
,
[3, 4, 5]
and
[6, 7]
returns the result
[10, 13, 5]
after adding together the corresponding array items.
-Distinct
Every unique combination of arguments will be aggregated only once. Repeating values are ignored.
Examples:
sum(DISTINCT x)
(or
sumDistinct(x)
),
groupArray(DISTINCT x)
(or
groupArrayDistinct(x)
),
corrStable(DISTINCT x, y)
(or
corrStableDistinct(x, y)
) and so on.
-OrDefault
Changes behavior of an aggregate function.
If an aggregate function does not have input values, with this combinator it returns the default value for its return data type. Applies to the aggregate functions that can take empty input data.
-OrDefault
can be used with other combinators.
Syntax
<
aggFunction
>
OrDefault
(
x
)
Arguments
x
— Aggregate function parameters.
Returned values
Returns the default value of an aggregate function's return type if there is nothing to aggregate.
Type depends on the aggregate function used.
Example
Query:
SELECT
avg
(
number
)
,
avgOrDefault
(
number
)
FROM
numbers
(
0
)
Result:
┌─avg(number)─┬─avgOrDefault(number)─┐
│ nan │ 0 │
└─────────────┴──────────────────────┘
Also
-OrDefault
can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
SELECT
avgOrDefaultIf
(
x
,
x
>
10
)
FROM
(
SELECT
toDecimal32
(
1.23
,
2
)
AS
x
)
Result:
┌─avgOrDefaultIf(x, greater(x, 10))─┐
│ 0.00 │
└───────────────────────────────────┘
-OrNull
Changes behavior of an aggregate function.
This combinator converts a result of an aggregate function to the
Nullable
data type. If the aggregate function does not have values to calculate it returns
NULL
.
-OrNull
can be used with other combinators.
Syntax
<
aggFunction
>
OrNull
(
x
)
Arguments
x
— Aggregate function parameters.
Returned values
The result of the aggregate function, converted to the
Nullable
data type.
NULL
, if there is nothing to aggregate.
Type:
Nullable(aggregate function return type)
.
Example
Add
-orNull
to the end of aggregate function.
Query:
SELECT
sumOrNull
(
number
)
,
toTypeName
(
sumOrNull
(
number
)
)
FROM
numbers
(
10
)
WHERE
number
>
10
Result:
┌─sumOrNull(number)─┬─toTypeName(sumOrNull(number))─┐
│ ᴺᵁᴸᴸ │ Nullable(UInt64) │
└───────────────────┴───────────────────────────────┘
Also
-OrNull
can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
SELECT
avgOrNullIf
(
x
,
x
>
10
)
FROM
(
SELECT
toDecimal32
(
1.23
,
2
)
AS
x
)
Result:
┌─avgOrNullIf(x, greater(x, 10))─┐
│ ᴺᵁᴸᴸ │
└────────────────────────────────┘
-Resample
Lets you divide data into groups, and then separately aggregates the data in those groups. Groups are created by splitting the values from one column into intervals.
<
aggFunction
>
Resample
(
start
,
end
,
step
)
(
<
aggFunction_params
>
,
resampling_key
)
Arguments
start
— Starting value of the whole required interval for
resampling_key
values.
stop
— Ending value of the whole required interval for
resampling_key
values. The whole interval does not include the
stop
value
[start, stop)
.
step
— Step for separating the whole interval into subintervals. The
aggFunction
is executed over each of those subintervals independently.
resampling_key
— Column whose values are used for separating data into intervals.
aggFunction_params
—
aggFunction
parameters.
Returned values
Array of
aggFunction
results for each subinterval.
Example
Consider the
people
table with the following data:
┌─name───┬─age─┬─wage─┐
│ John │ 16 │ 10 │
│ Alice │ 30 │ 15 │
│ Mary │ 35 │ 8 │
│ Evelyn │ 48 │ 11.5 │
│ David │ 62 │ 9.9 │
│ Brian │ 60 │ 16 │
└────────┴─────┴──────┘
Let's get the names of the people whose age lies in the intervals of
[30,60)
and
[60,75)
. Since we use integer representation for age, we get ages in the
[30, 59]
and
[60,74]
intervals.
To aggregate names in an array, we use the
groupArray
aggregate function. It takes one argument. In our case, it's the
name
column. The
groupArrayResample
function should use the
age
column to aggregate names by age. To define the required intervals, we pass the
30, 75, 30
arguments into the
groupArrayResample
function.
SELECT
groupArrayResample
(
30
,
75
,
30
)
(
name
,
age
)
FROM
people
┌─groupArrayResample(30, 75, 30)(name, age)─────┐
│ [['Alice','Mary','Evelyn'],['David','Brian']] │
└───────────────────────────────────────────────┘
Consider the results.
John
is out of the sample because he's too young. Other people are distributed according to the specified age intervals.
Now let's count the total number of people and their average wage in the specified age intervals.
SELECT
countResample
(
30
,
75
,
30
)
(
name
,
age
)
AS
amount
,
avgResample
(
30
,
75
,
30
)
(
wage
,
age
)
AS
avg_wage
FROM
people
┌─amount─┬─avg_wage──────────────────┐
│ [3,2] │ [11.5,12.949999809265137] │
└────────┴───────────────────────────┘
-ArgMin
The suffix -ArgMin can be appended to the name of any aggregate function. In this case, the aggregate function accepts an additional argument, which should be any comparable expression. The aggregate function processes only the rows that have the minimum value for the specified extra expression.
Examples:
sumArgMin(column, expr)
,
countArgMin(expr)
,
avgArgMin(x, expr)
and so on.
-ArgMax
Similar to suffix -ArgMin but processes only the rows that have the maximum value for the specified extra expression.
Related Content
Blog:
Using Aggregate Combinators in ClickHouse |
| Markdown | [Skip to main content](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#__docusaurus_skipToContent_fallback)
[](https://clickhouse.com/)
- [Products](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [ClickHouse Cloud Best way to use ClickHouse. Available on AWS, GCP, and Azure.](https://clickhouse.com/cloud)
- [BYOC (Bring Your Own Cloud) The fully managed ClickHouse Cloud service, Can be deployed in your AWS account.](https://clickhouse.com/cloud/bring-your-own-cloud)
- [ClickHouse Set up a database with open-source ClickHouse. ClickHouse](https://clickhouse.com/clickhouse)
- [Discover more than 100 integrations.](https://clickhouse.com/integrations)
[Discover more than 100 integrations.](https://clickhouse.com/integrations)
- [Use cases](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [Real-time analytics](https://clickhouse.com/use-cases/real-time-analytics)
- [Machine Learning & Generative AI](https://clickhouse.com/use-cases/machine-learning-and-data-science)
- [Business Intelligence](https://clickhouse.com/use-cases/data-warehousing)
- [Logs, Events, Traces](https://clickhouse.com/use-cases/observability)
- [All use cases](https://clickhouse.com/use-cases)
[All use cases](https://clickhouse.com/use-cases)
- [Documentation](https://clickhouse.com/docs)
- [Resources](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [User stories](https://clickhouse.com/user-stories)
- [Blog](https://clickhouse.com/blog)
- [Events](https://clickhouse.com/company/events)
- [Learning and certification](https://clickhouse.com/learn)
- [Comparison](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [BigQuery](https://clickhouse.com/comparison/bigquery)
- [PostgreSQL](https://clickhouse.com/comparison/postgresql)
- [Redshift](https://clickhouse.com/comparison/redshift)
- [Rockset](https://clickhouse.com/comparison/rockset)
- [Snowflake](https://clickhouse.com/comparison/snowflake)
- [Video](https://clickhouse.com/videos)
- [Demo](https://clickhouse.com/demos)
- [Pricing](https://clickhouse.com/pricing)
- [Contact](https://clickhouse.com/company/contact?loc=nav)
[46\.7k](https://github.com/ClickHouse/ClickHouse?utm_source=clickhouse&utm_medium=website&utm_campaign=website-nav)
[Search`Ctrl``K`](https://clickhouse.com/docs/search)
[Sign in](https://console.clickhouse.cloud/signIn?loc=docs-nav-signIn-cta&glxid=43f221c6-40d4-4576-931b-74d90e353b1e&pagePath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&origPath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&utm_ga=GA1.1.657831716.1775290767)
[Get started](https://console.clickhouse.cloud/signUp?loc=docs-nav-signUp-cta&glxid=43f221c6-40d4-4576-931b-74d90e353b1e&pagePath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&origPath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&utm_ga=GA1.1.657831716.1775290767)
[Get started](https://clickhouse.com/docs/introduction-clickhouse)
[Cloud](https://clickhouse.com/docs/cloud/overview)
[Manage data](https://clickhouse.com/docs/updating-data)
[Server admin](https://clickhouse.com/docs/guides/manage-and-deploy-index)
[Reference](https://clickhouse.com/docs/sql-reference)
[Integrations](https://clickhouse.com/docs/integrations)
[ClickStack](https://clickhouse.com/docs/use-cases/observability/clickstack/overview)
[chDB](https://clickhouse.com/docs/chdb)
[About](https://clickhouse.com/docs/about)
[Knowledge Base](https://clickhouse.com/docs/knowledgebase)
[English](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [English](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [日本語](https://clickhouse.com/docs/jp/sql-reference/aggregate-functions/combinators)
- [中文](https://clickhouse.com/docs/zh/sql-reference/aggregate-functions/combinators)
- [Русский](https://clickhouse.com/docs/ru/sql-reference/aggregate-functions/combinators)
- [한국어](https://clickhouse.com/docs/ko/sql-reference/aggregate-functions/combinators)
[Skip to main content](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#__docusaurus_skipToContent_fallback)
[](https://clickhouse.com/)
- [Products](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [ClickHouse Cloud Best way to use ClickHouse. Available on AWS, GCP, and Azure.](https://clickhouse.com/cloud)
- [BYOC (Bring Your Own Cloud) The fully managed ClickHouse Cloud service, Can be deployed in your AWS account.](https://clickhouse.com/cloud/bring-your-own-cloud)
- [ClickHouse Set up a database with open-source ClickHouse. ClickHouse](https://clickhouse.com/clickhouse)
- [Discover more than 100 integrations.](https://clickhouse.com/integrations)
[Discover more than 100 integrations.](https://clickhouse.com/integrations)
- [Use cases](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [Real-time analytics](https://clickhouse.com/use-cases/real-time-analytics)
- [Machine Learning & Generative AI](https://clickhouse.com/use-cases/machine-learning-and-data-science)
- [Business Intelligence](https://clickhouse.com/use-cases/data-warehousing)
- [Logs, Events, Traces](https://clickhouse.com/use-cases/observability)
- [All use cases](https://clickhouse.com/use-cases)
[All use cases](https://clickhouse.com/use-cases)
- [Documentation](https://clickhouse.com/docs)
- [Resources](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [User stories](https://clickhouse.com/user-stories)
- [Blog](https://clickhouse.com/blog)
- [Events](https://clickhouse.com/company/events)
- [Learning and certification](https://clickhouse.com/learn)
- [Comparison](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [BigQuery](https://clickhouse.com/comparison/bigquery)
- [PostgreSQL](https://clickhouse.com/comparison/postgresql)
- [Redshift](https://clickhouse.com/comparison/redshift)
- [Rockset](https://clickhouse.com/comparison/rockset)
- [Snowflake](https://clickhouse.com/comparison/snowflake)
- [Video](https://clickhouse.com/videos)
- [Demo](https://clickhouse.com/demos)
- [Pricing](https://clickhouse.com/pricing)
- [Contact](https://clickhouse.com/company/contact?loc=nav)
[46\.7k](https://github.com/ClickHouse/ClickHouse?utm_source=clickhouse&utm_medium=website&utm_campaign=website-nav)
[Search`Ctrl``K`](https://clickhouse.com/docs/search)
[Sign in](https://console.clickhouse.cloud/signIn?loc=docs-nav-signIn-cta&glxid=43f221c6-40d4-4576-931b-74d90e353b1e&pagePath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&origPath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&utm_ga=GA1.1.657831716.1775290767)
[Get started](https://console.clickhouse.cloud/signUp?loc=docs-nav-signUp-cta&glxid=43f221c6-40d4-4576-931b-74d90e353b1e&pagePath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&origPath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&utm_ga=GA1.1.657831716.1775290767)
[Get started](https://clickhouse.com/docs/introduction-clickhouse)
[Cloud](https://clickhouse.com/docs/cloud/overview)
[Manage data](https://clickhouse.com/docs/updating-data)
[Server admin](https://clickhouse.com/docs/guides/manage-and-deploy-index)
[Reference](https://clickhouse.com/docs/sql-reference)
[Integrations](https://clickhouse.com/docs/integrations)
[ClickStack](https://clickhouse.com/docs/use-cases/observability/clickstack/overview)
[chDB](https://clickhouse.com/docs/chdb)
[About](https://clickhouse.com/docs/about)
[Knowledge Base](https://clickhouse.com/docs/knowledgebase)
[English](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [English](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [日本語](https://clickhouse.com/docs/jp/sql-reference/aggregate-functions/combinators)
- [中文](https://clickhouse.com/docs/zh/sql-reference/aggregate-functions/combinators)
- [Русский](https://clickhouse.com/docs/ru/sql-reference/aggregate-functions/combinators)
- [한국어](https://clickhouse.com/docs/ko/sql-reference/aggregate-functions/combinators)
[Search`Ctrl``K`](https://clickhouse.com/docs/search)
- [Introduction](https://clickhouse.com/docs/sql-reference)
- [Syntax](https://clickhouse.com/docs/sql-reference/syntax)
- [Input and Output Formats](https://clickhouse.com/docs/sql-reference/formats)
- [Data types](https://clickhouse.com/docs/sql-reference/data-types)
- [Statements](https://clickhouse.com/docs/sql-reference/statements)
- [Operators](https://clickhouse.com/docs/sql-reference/operators)
- [Engines](https://clickhouse.com/docs/engines)
- [Database Engines](https://clickhouse.com/docs/engines/database-engines)
- [Table Engines](https://clickhouse.com/docs/engines/table-engines)
- [Functions](https://clickhouse.com/docs/sql-reference/functions)
- [Regular functions](https://clickhouse.com/docs/sql-reference/functions/regular-functions)
- [Aggregate functions](https://clickhouse.com/docs/sql-reference/aggregate-functions)
- [Aggregate Functions](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference)
- [Combinators](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [Parametric](https://clickhouse.com/docs/sql-reference/aggregate-functions/parametric-functions)
- [GROUPING](https://clickhouse.com/docs/sql-reference/aggregate-functions/grouping_function)
- [Combinator examples](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [Table functions](https://clickhouse.com/docs/sql-reference/table-functions)
- [Window functions](https://clickhouse.com/docs/sql-reference/window-functions)
- [Formats](https://clickhouse.com/docs/interfaces/formats)
- [Data Lakes](https://clickhouse.com/docs/sql-reference/datalakes)
- [Functions](https://clickhouse.com/docs/sql-reference/functions)
- [Aggregate functions](https://clickhouse.com/docs/sql-reference/aggregate-functions)
- Combinators
[Edit this page](https://github.com/ClickHouse/ClickHouse/tree/master/docs/en/sql-reference/aggregate-functions/combinators.md)
# Aggregate function combinators
The name of an aggregate function can have a suffix appended to it. This changes the way the aggregate function works.
## \-If[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-if "Direct link to -If")
The suffix -If can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument – a condition (Uint8 type). The aggregate function processes only the rows that trigger the condition. If the condition was not triggered even once, it returns a default value (usually zeros or empty strings).
Examples: `sumIf(column, cond)`, `countIf(cond)`, `avgIf(x, cond)`, `quantilesTimingIf(level1, level2)(x, cond)`, `argMinIf(arg, val, cond)` and so on.
With conditional aggregate functions, you can calculate aggregates for several conditions at once, without using subqueries and `JOIN`s. For example, conditional aggregate functions can be used to implement the segment comparison functionality.
## \-Array[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-array "Direct link to -Array")
The -Array suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. When processing arrays, the aggregate function works like the original aggregate function across all array elements.
Example 1: `sumArray(arr)` - Totals all the elements of all 'arr' arrays. In this example, it could have been written more simply: `sum(arraySum(arr))`.
Example 2: `uniqArray(arr)` – Counts the number of unique elements in all 'arr' arrays. This could be done an easier way: `uniq(arrayJoin(arr))`, but it's not always possible to add 'arrayJoin' to a query.
\-If and -Array can be combined. However, 'Array' must come first, then 'If'. Examples: `uniqArrayIf(arr, cond)`, `quantilesTimingArrayIf(level1, level2)(arr, cond)`. Due to this order, the 'cond' argument won't be an array.
## \-Map[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-map "Direct link to -Map")
The -Map suffix can be appended to any aggregate function. This will create an aggregate function which gets Map type as an argument, and aggregates values of each key of the map separately using the specified aggregate function. The result is also of a Map type.
**Example**
```
CREATE TABLE map_map(
date Date,
timeslot DateTime,
status Map(String, UInt64)
) ENGINE = MergeTree
ORDER BY ();
INSERT INTO map_map VALUES
('2000-01-01', '2000-01-01 00:00:00', (['a', 'b', 'c'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:00:00', (['c', 'd', 'e'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:01:00', (['d', 'e', 'f'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:01:00', (['f', 'g', 'g'], [10, 10, 10]));
SELECT
timeslot,
sumMap(status),
avgMap(status),
minMap(status)
FROM map_map
GROUP BY timeslot;
┌────────────timeslot─┬─sumMap(status)───────────────────────┬─avgMap(status)───────────────────────┬─minMap(status)───────────────────────┐
│ 2000-01-01 00:00:00 │ {'a':10,'b':10,'c':20,'d':10,'e':10} │ {'a':10,'b':10,'c':10,'d':10,'e':10} │ {'a':10,'b':10,'c':10,'d':10,'e':10} │
│ 2000-01-01 00:01:00 │ {'d':10,'e':10,'f':20,'g':20} │ {'d':10,'e':10,'f':10,'g':10} │ {'d':10,'e':10,'f':10,'g':10} │
└─────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┘
```
## \-SimpleState[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-simplestate "Direct link to -SimpleState")
If you apply this combinator, the aggregate function returns the same value but with a different type. This is a [SimpleAggregateFunction(...)](https://clickhouse.com/docs/sql-reference/data-types/simpleaggregatefunction) that can be stored in a table to work with [AggregatingMergeTree](https://clickhouse.com/docs/engines/table-engines/mergetree-family/aggregatingmergetree) tables.
**Syntax**
```
<aggFunction>SimpleState(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
The value of an aggregate function with the `SimpleAggregateFunction(...)` type.
**Example**
Query:
```
WITH anySimpleState(number) AS c SELECT toTypeName(c), c FROM numbers(1);
```
Result:
```
┌─toTypeName(c)────────────────────────┬─c─┐
│ SimpleAggregateFunction(any, UInt64) │ 0 │
└──────────────────────────────────────┴───┘
```
## \-State[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-state "Direct link to -State")
If you apply this combinator, the aggregate function does not return the resulting value (such as the number of unique values for the [uniq](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/uniq) function), but an intermediate state of the aggregation (for `uniq`, this is the hash table for calculating the number of unique values). This is an `AggregateFunction(...)` that can be used for further processing or stored in a table to finish aggregating later.
Note
Please notice, that -MapState is not an invariant for the same data due to the fact that order of data in intermediate state can change, though it doesn't impact ingestion of this data.
To work with these states, use:
- [AggregatingMergeTree](https://clickhouse.com/docs/engines/table-engines/mergetree-family/aggregatingmergetree) table engine.
- [finalizeAggregation](https://clickhouse.com/docs/sql-reference/functions/other-functions#finalizeAggregation) function.
- [runningAccumulate](https://clickhouse.com/docs/sql-reference/functions/other-functions#runningAccumulate) function.
- [\-Merge](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-merge) combinator.
- [\-MergeState](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-mergestate) combinator.
## \-Merge[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-merge "Direct link to -Merge")
If you apply this combinator, the aggregate function takes the intermediate aggregation state as an argument, combines the states to finish aggregation, and returns the resulting value.
## \-MergeState[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-mergestate "Direct link to -MergeState")
Merges the intermediate aggregation states in the same way as the -Merge combinator. However, it does not return the resulting value, but an intermediate aggregation state, similar to the -State combinator.
## \-ForEach[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-foreach "Direct link to -ForEach")
Converts an aggregate function for tables into an aggregate function for arrays that aggregates the corresponding array items and returns an array of results. For example, `sumForEach` for the arrays `[1, 2]`, `[3, 4, 5]`and`[6, 7]`returns the result `[10, 13, 5]` after adding together the corresponding array items.
## \-Distinct[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-distinct "Direct link to -Distinct")
Every unique combination of arguments will be aggregated only once. Repeating values are ignored. Examples: `sum(DISTINCT x)` (or `sumDistinct(x)`), `groupArray(DISTINCT x)` (or `groupArrayDistinct(x)`), `corrStable(DISTINCT x, y)` (or `corrStableDistinct(x, y)`) and so on.
## \-OrDefault[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ordefault "Direct link to -OrDefault")
Changes behavior of an aggregate function.
If an aggregate function does not have input values, with this combinator it returns the default value for its return data type. Applies to the aggregate functions that can take empty input data.
`-OrDefault` can be used with other combinators.
**Syntax**
```
<aggFunction>OrDefault(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
Returns the default value of an aggregate function's return type if there is nothing to aggregate.
Type depends on the aggregate function used.
**Example**
Query:
```
SELECT avg(number), avgOrDefault(number) FROM numbers(0)
```
Result:
```
┌─avg(number)─┬─avgOrDefault(number)─┐
│ nan │ 0 │
└─────────────┴──────────────────────┘
```
Also `-OrDefault` can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
```
SELECT avgOrDefaultIf(x, x > 10)
FROM
(
SELECT toDecimal32(1.23, 2) AS x
)
```
Result:
```
┌─avgOrDefaultIf(x, greater(x, 10))─┐
│ 0.00 │
└───────────────────────────────────┘
```
## \-OrNull[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ornull "Direct link to -OrNull")
Changes behavior of an aggregate function.
This combinator converts a result of an aggregate function to the [Nullable](https://clickhouse.com/docs/sql-reference/data-types/nullable) data type. If the aggregate function does not have values to calculate it returns [NULL](https://clickhouse.com/docs/operations/settings/formats#input_format_null_as_default).
`-OrNull` can be used with other combinators.
**Syntax**
```
<aggFunction>OrNull(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
- The result of the aggregate function, converted to the `Nullable` data type.
- `NULL`, if there is nothing to aggregate.
Type: `Nullable(aggregate function return type)`.
**Example**
Add `-orNull` to the end of aggregate function.
Query:
```
SELECT sumOrNull(number), toTypeName(sumOrNull(number)) FROM numbers(10) WHERE number > 10
```
Result:
```
┌─sumOrNull(number)─┬─toTypeName(sumOrNull(number))─┐
│ ᴺᵁᴸᴸ │ Nullable(UInt64) │
└───────────────────┴───────────────────────────────┘
```
Also `-OrNull` can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
```
SELECT avgOrNullIf(x, x > 10)
FROM
(
SELECT toDecimal32(1.23, 2) AS x
)
```
Result:
```
┌─avgOrNullIf(x, greater(x, 10))─┐
│ ᴺᵁᴸᴸ │
└────────────────────────────────┘
```
## \-Resample[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-resample "Direct link to -Resample")
Lets you divide data into groups, and then separately aggregates the data in those groups. Groups are created by splitting the values from one column into intervals.
```
<aggFunction>Resample(start, end, step)(<aggFunction_params>, resampling_key)
```
**Arguments**
- `start` — Starting value of the whole required interval for `resampling_key` values.
- `stop` — Ending value of the whole required interval for `resampling_key` values. The whole interval does not include the `stop` value `[start, stop)`.
- `step` — Step for separating the whole interval into subintervals. The `aggFunction` is executed over each of those subintervals independently.
- `resampling_key` — Column whose values are used for separating data into intervals.
- `aggFunction_params` — `aggFunction` parameters.
**Returned values**
- Array of `aggFunction` results for each subinterval.
**Example**
Consider the `people` table with the following data:
```
┌─name───┬─age─┬─wage─┐
│ John │ 16 │ 10 │
│ Alice │ 30 │ 15 │
│ Mary │ 35 │ 8 │
│ Evelyn │ 48 │ 11.5 │
│ David │ 62 │ 9.9 │
│ Brian │ 60 │ 16 │
└────────┴─────┴──────┘
```
Let's get the names of the people whose age lies in the intervals of `[30,60)` and `[60,75)`. Since we use integer representation for age, we get ages in the `[30, 59]` and `[60,74]` intervals.
To aggregate names in an array, we use the [groupArray](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/grouparray) aggregate function. It takes one argument. In our case, it's the `name` column. The `groupArrayResample` function should use the `age` column to aggregate names by age. To define the required intervals, we pass the `30, 75, 30` arguments into the `groupArrayResample` function.
```
SELECT groupArrayResample(30, 75, 30)(name, age) FROM people
```
```
┌─groupArrayResample(30, 75, 30)(name, age)─────┐
│ [['Alice','Mary','Evelyn'],['David','Brian']] │
└───────────────────────────────────────────────┘
```
Consider the results.
`John` is out of the sample because he's too young. Other people are distributed according to the specified age intervals.
Now let's count the total number of people and their average wage in the specified age intervals.
```
SELECT
countResample(30, 75, 30)(name, age) AS amount,
avgResample(30, 75, 30)(wage, age) AS avg_wage
FROM people
```
```
┌─amount─┬─avg_wage──────────────────┐
│ [3,2] │ [11.5,12.949999809265137] │
└────────┴───────────────────────────┘
```
## \-ArgMin[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmin "Direct link to -ArgMin")
The suffix -ArgMin can be appended to the name of any aggregate function. In this case, the aggregate function accepts an additional argument, which should be any comparable expression. The aggregate function processes only the rows that have the minimum value for the specified extra expression.
Examples: `sumArgMin(column, expr)`, `countArgMin(expr)`, `avgArgMin(x, expr)` and so on.
## \-ArgMax[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmax "Direct link to -ArgMax")
Similar to suffix -ArgMin but processes only the rows that have the maximum value for the specified extra expression.
## Related Content[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#related-content "Direct link to Related Content")
- Blog: [Using Aggregate Combinators in ClickHouse](https://clickhouse.com/blog/aggregate-functions-combinators-in-clickhouse-for-arrays-maps-and-states)
[Previous welchTTest](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/welchttest)
[Next Parametric](https://clickhouse.com/docs/sql-reference/aggregate-functions/parametric-functions)
- [\-If](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-if)
- [\-Array](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-array)
- [\-Map](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-map)
- [\-SimpleState](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-simplestate)
- [\-State](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-state)
- [\-Merge](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-merge)
- [\-MergeState](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-mergestate)
- [\-ForEach](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-foreach)
- [\-Distinct](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-distinct)
- [\-OrDefault](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ordefault)
- [\-OrNull](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ornull)
- [\-Resample](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-resample)
- [\-ArgMin](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmin)
- [\-ArgMax](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmax)
- [Related Content](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#related-content)
Was this page helpful?
###### Try ClickHouse Cloud for FREE
Separation of storage and compute, automatic scaling, built-in SQL console, and lots more. \$300 in free credits when signing up.
[Try it for Free](https://console.clickhouse.cloud/signUp?loc=doc-card-banner&glxid=43f221c6-40d4-4576-931b-74d90e353b1e&pagePath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&origPath=%2Fdocs%2Fsql-reference%2Faggregate-functions%2Fcombinators&utm_ga=GA1.1.657831716.1775290767)
© 2016–2026 ClickHouse, Inc.
[Trademark](https://clickhouse.com/legal/trademark-policy)·[Privacy](https://clickhouse.com/legal/privacy-policy)·[Security](https://trust.clickhouse.com/)·[Terms of Service](https://clickhouse.com/legal/agreements/terms-of-service)

© 2016–2026 ClickHouse, Inc.
[Trademark](https://clickhouse.com/legal/trademark-policy)·[Privacy](https://clickhouse.com/legal/privacy-policy)·[Security](https://trust.clickhouse.com/)·[Terms of Service](https://clickhouse.com/legal/agreements/terms-of-service)

[](https://clickhouse.com/)
EN
- Get started▼
- Cloud▼
- Manage data▼
- Server admin▼
- Reference▼
- Integrations▼
- ClickStack▼
- chDB▼
- About▼
[](https://clickhouse.com/)
EN
main-menu
- Introduction▼
- [Syntax](https://clickhouse.com/docs/sql-reference/syntax)
- [Input and Output Formats](https://clickhouse.com/docs/sql-reference/formats)
- Data types▼
- Statements▼
- Operators▼
- Engines▼
- Functions▼
- Regular functions▼
- Aggregate functions▼
- Aggregate Functions▼
- [Combinators](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators)
- [Parametric](https://clickhouse.com/docs/sql-reference/aggregate-functions/parametric-functions)
- [GROUPING](https://clickhouse.com/docs/sql-reference/aggregate-functions/grouping_function)
- Combinator examples▼
- Table functions▼
- Window functions▼
- Formats▼
- [Data Lakes](https://clickhouse.com/docs/sql-reference/datalakes) |
| Readable Markdown | The name of an aggregate function can have a suffix appended to it. This changes the way the aggregate function works.
## \-If[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-if "Direct link to -If")
The suffix -If can be appended to the name of any aggregate function. In this case, the aggregate function accepts an extra argument – a condition (Uint8 type). The aggregate function processes only the rows that trigger the condition. If the condition was not triggered even once, it returns a default value (usually zeros or empty strings).
Examples: `sumIf(column, cond)`, `countIf(cond)`, `avgIf(x, cond)`, `quantilesTimingIf(level1, level2)(x, cond)`, `argMinIf(arg, val, cond)` and so on.
With conditional aggregate functions, you can calculate aggregates for several conditions at once, without using subqueries and `JOIN`s. For example, conditional aggregate functions can be used to implement the segment comparison functionality.
## \-Array[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-array "Direct link to -Array")
The -Array suffix can be appended to any aggregate function. In this case, the aggregate function takes arguments of the 'Array(T)' type (arrays) instead of 'T' type arguments. If the aggregate function accepts multiple arguments, this must be arrays of equal lengths. When processing arrays, the aggregate function works like the original aggregate function across all array elements.
Example 1: `sumArray(arr)` - Totals all the elements of all 'arr' arrays. In this example, it could have been written more simply: `sum(arraySum(arr))`.
Example 2: `uniqArray(arr)` – Counts the number of unique elements in all 'arr' arrays. This could be done an easier way: `uniq(arrayJoin(arr))`, but it's not always possible to add 'arrayJoin' to a query.
\-If and -Array can be combined. However, 'Array' must come first, then 'If'. Examples: `uniqArrayIf(arr, cond)`, `quantilesTimingArrayIf(level1, level2)(arr, cond)`. Due to this order, the 'cond' argument won't be an array.
## \-Map[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-map "Direct link to -Map")
The -Map suffix can be appended to any aggregate function. This will create an aggregate function which gets Map type as an argument, and aggregates values of each key of the map separately using the specified aggregate function. The result is also of a Map type.
**Example**
```
CREATE TABLE map_map(
date Date,
timeslot DateTime,
status Map(String, UInt64)
) ENGINE = MergeTree
ORDER BY ();
INSERT INTO map_map VALUES
('2000-01-01', '2000-01-01 00:00:00', (['a', 'b', 'c'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:00:00', (['c', 'd', 'e'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:01:00', (['d', 'e', 'f'], [10, 10, 10])),
('2000-01-01', '2000-01-01 00:01:00', (['f', 'g', 'g'], [10, 10, 10]));
SELECT
timeslot,
sumMap(status),
avgMap(status),
minMap(status)
FROM map_map
GROUP BY timeslot;
┌────────────timeslot─┬─sumMap(status)───────────────────────┬─avgMap(status)───────────────────────┬─minMap(status)───────────────────────┐
│ 2000-01-01 00:00:00 │ {'a':10,'b':10,'c':20,'d':10,'e':10} │ {'a':10,'b':10,'c':10,'d':10,'e':10} │ {'a':10,'b':10,'c':10,'d':10,'e':10} │
│ 2000-01-01 00:01:00 │ {'d':10,'e':10,'f':20,'g':20} │ {'d':10,'e':10,'f':10,'g':10} │ {'d':10,'e':10,'f':10,'g':10} │
└─────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┴──────────────────────────────────────┘
```
## \-SimpleState[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-simplestate "Direct link to -SimpleState")
If you apply this combinator, the aggregate function returns the same value but with a different type. This is a [SimpleAggregateFunction(...)](https://clickhouse.com/docs/sql-reference/data-types/simpleaggregatefunction) that can be stored in a table to work with [AggregatingMergeTree](https://clickhouse.com/docs/engines/table-engines/mergetree-family/aggregatingmergetree) tables.
**Syntax**
```
<aggFunction>SimpleState(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
The value of an aggregate function with the `SimpleAggregateFunction(...)` type.
**Example**
Query:
```
WITH anySimpleState(number) AS c SELECT toTypeName(c), c FROM numbers(1);
```
Result:
```
┌─toTypeName(c)────────────────────────┬─c─┐
│ SimpleAggregateFunction(any, UInt64) │ 0 │
└──────────────────────────────────────┴───┘
```
## \-State[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-state "Direct link to -State")
If you apply this combinator, the aggregate function does not return the resulting value (such as the number of unique values for the [uniq](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/uniq) function), but an intermediate state of the aggregation (for `uniq`, this is the hash table for calculating the number of unique values). This is an `AggregateFunction(...)` that can be used for further processing or stored in a table to finish aggregating later.
Note
Please notice, that -MapState is not an invariant for the same data due to the fact that order of data in intermediate state can change, though it doesn't impact ingestion of this data.
To work with these states, use:
- [AggregatingMergeTree](https://clickhouse.com/docs/engines/table-engines/mergetree-family/aggregatingmergetree) table engine.
- [finalizeAggregation](https://clickhouse.com/docs/sql-reference/functions/other-functions#finalizeAggregation) function.
- [runningAccumulate](https://clickhouse.com/docs/sql-reference/functions/other-functions#runningAccumulate) function.
- [\-Merge](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-merge) combinator.
- [\-MergeState](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-mergestate) combinator.
## \-Merge[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-merge "Direct link to -Merge")
If you apply this combinator, the aggregate function takes the intermediate aggregation state as an argument, combines the states to finish aggregation, and returns the resulting value.
## \-MergeState[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-mergestate "Direct link to -MergeState")
Merges the intermediate aggregation states in the same way as the -Merge combinator. However, it does not return the resulting value, but an intermediate aggregation state, similar to the -State combinator.
## \-ForEach[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-foreach "Direct link to -ForEach")
Converts an aggregate function for tables into an aggregate function for arrays that aggregates the corresponding array items and returns an array of results. For example, `sumForEach` for the arrays `[1, 2]`, `[3, 4, 5]`and`[6, 7]`returns the result `[10, 13, 5]` after adding together the corresponding array items.
## \-Distinct[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-distinct "Direct link to -Distinct")
Every unique combination of arguments will be aggregated only once. Repeating values are ignored. Examples: `sum(DISTINCT x)` (or `sumDistinct(x)`), `groupArray(DISTINCT x)` (or `groupArrayDistinct(x)`), `corrStable(DISTINCT x, y)` (or `corrStableDistinct(x, y)`) and so on.
## \-OrDefault[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ordefault "Direct link to -OrDefault")
Changes behavior of an aggregate function.
If an aggregate function does not have input values, with this combinator it returns the default value for its return data type. Applies to the aggregate functions that can take empty input data.
`-OrDefault` can be used with other combinators.
**Syntax**
```
<aggFunction>OrDefault(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
Returns the default value of an aggregate function's return type if there is nothing to aggregate.
Type depends on the aggregate function used.
**Example**
Query:
```
SELECT avg(number), avgOrDefault(number) FROM numbers(0)
```
Result:
```
┌─avg(number)─┬─avgOrDefault(number)─┐
│ nan │ 0 │
└─────────────┴──────────────────────┘
```
Also `-OrDefault` can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
```
SELECT avgOrDefaultIf(x, x > 10)
FROM
(
SELECT toDecimal32(1.23, 2) AS x
)
```
Result:
```
┌─avgOrDefaultIf(x, greater(x, 10))─┐
│ 0.00 │
└───────────────────────────────────┘
```
## \-OrNull[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-ornull "Direct link to -OrNull")
Changes behavior of an aggregate function.
This combinator converts a result of an aggregate function to the [Nullable](https://clickhouse.com/docs/sql-reference/data-types/nullable) data type. If the aggregate function does not have values to calculate it returns [NULL](https://clickhouse.com/docs/operations/settings/formats#input_format_null_as_default).
`-OrNull` can be used with other combinators.
**Syntax**
```
<aggFunction>OrNull(x)
```
**Arguments**
- `x` — Aggregate function parameters.
**Returned values**
- The result of the aggregate function, converted to the `Nullable` data type.
- `NULL`, if there is nothing to aggregate.
Type: `Nullable(aggregate function return type)`.
**Example**
Add `-orNull` to the end of aggregate function.
Query:
```
SELECT sumOrNull(number), toTypeName(sumOrNull(number)) FROM numbers(10) WHERE number > 10
```
Result:
```
┌─sumOrNull(number)─┬─toTypeName(sumOrNull(number))─┐
│ ᴺᵁᴸᴸ │ Nullable(UInt64) │
└───────────────────┴───────────────────────────────┘
```
Also `-OrNull` can be used with another combinators. It is useful when the aggregate function does not accept the empty input.
Query:
```
SELECT avgOrNullIf(x, x > 10)
FROM
(
SELECT toDecimal32(1.23, 2) AS x
)
```
Result:
```
┌─avgOrNullIf(x, greater(x, 10))─┐
│ ᴺᵁᴸᴸ │
└────────────────────────────────┘
```
## \-Resample[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-resample "Direct link to -Resample")
Lets you divide data into groups, and then separately aggregates the data in those groups. Groups are created by splitting the values from one column into intervals.
```
<aggFunction>Resample(start, end, step)(<aggFunction_params>, resampling_key)
```
**Arguments**
- `start` — Starting value of the whole required interval for `resampling_key` values.
- `stop` — Ending value of the whole required interval for `resampling_key` values. The whole interval does not include the `stop` value `[start, stop)`.
- `step` — Step for separating the whole interval into subintervals. The `aggFunction` is executed over each of those subintervals independently.
- `resampling_key` — Column whose values are used for separating data into intervals.
- `aggFunction_params` — `aggFunction` parameters.
**Returned values**
- Array of `aggFunction` results for each subinterval.
**Example**
Consider the `people` table with the following data:
```
┌─name───┬─age─┬─wage─┐
│ John │ 16 │ 10 │
│ Alice │ 30 │ 15 │
│ Mary │ 35 │ 8 │
│ Evelyn │ 48 │ 11.5 │
│ David │ 62 │ 9.9 │
│ Brian │ 60 │ 16 │
└────────┴─────┴──────┘
```
Let's get the names of the people whose age lies in the intervals of `[30,60)` and `[60,75)`. Since we use integer representation for age, we get ages in the `[30, 59]` and `[60,74]` intervals.
To aggregate names in an array, we use the [groupArray](https://clickhouse.com/docs/sql-reference/aggregate-functions/reference/grouparray) aggregate function. It takes one argument. In our case, it's the `name` column. The `groupArrayResample` function should use the `age` column to aggregate names by age. To define the required intervals, we pass the `30, 75, 30` arguments into the `groupArrayResample` function.
```
SELECT groupArrayResample(30, 75, 30)(name, age) FROM people
```
```
┌─groupArrayResample(30, 75, 30)(name, age)─────┐
│ [['Alice','Mary','Evelyn'],['David','Brian']] │
└───────────────────────────────────────────────┘
```
Consider the results.
`John` is out of the sample because he's too young. Other people are distributed according to the specified age intervals.
Now let's count the total number of people and their average wage in the specified age intervals.
```
SELECT
countResample(30, 75, 30)(name, age) AS amount,
avgResample(30, 75, 30)(wage, age) AS avg_wage
FROM people
```
```
┌─amount─┬─avg_wage──────────────────┐
│ [3,2] │ [11.5,12.949999809265137] │
└────────┴───────────────────────────┘
```
## \-ArgMin[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmin "Direct link to -ArgMin")
The suffix -ArgMin can be appended to the name of any aggregate function. In this case, the aggregate function accepts an additional argument, which should be any comparable expression. The aggregate function processes only the rows that have the minimum value for the specified extra expression.
Examples: `sumArgMin(column, expr)`, `countArgMin(expr)`, `avgArgMin(x, expr)` and so on.
## \-ArgMax[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#-argmax "Direct link to -ArgMax")
Similar to suffix -ArgMin but processes only the rows that have the maximum value for the specified extra expression.
## Related Content[](https://clickhouse.com/docs/sql-reference/aggregate-functions/combinators#related-content "Direct link to Related Content")
- Blog: [Using Aggregate Combinators in ClickHouse](https://clickhouse.com/blog/aggregate-functions-combinators-in-clickhouse-for-arrays-maps-and-states) |
| Shard | 89 (laksa) |
| Root Hash | 12633450985039531489 |
| Unparsed URL | com,clickhouse!/docs/sql-reference/aggregate-functions/combinators s443 |