Aggregates and Window Functions
This page covers aggregate functions, the GROUP BY forms (ROLLUP, CUBE, GROUPING SETS), HAVING, and window functions with their frames. Scalar functions are on Functions and operators.
Aggregate functions
The parser recognises an aggregate by name in parse_function_call and builds Expr::Aggregate { func, args, distinct, filter, order_by }. The function is one variant of AggregateFunc.
| SQL name | AggregateFunc |
Result type (PostgreSQL dialect) | Notes |
|---|---|---|---|
count(*), count(x)
|
Count |
int8 |
count(x) skips NULL |
count(DISTINCT x) |
CountDistinct |
int8 | |
sum(x) |
Sum |
int8 for int2/int4 input; numeric for int8 and numeric; float4 for float4; float8 for float8 | NULL over zero rows |
avg(x) |
Avg |
float8 for float input; numeric otherwise | |
min(x), max(x)
|
Min, Max
|
type of the argument | |
array_agg(x [ORDER BY ...]) |
ArrayAgg |
array of the argument type | Keeps NULL elements; NULL over zero rows |
string_agg(x, sep [ORDER BY ...]) |
StringAgg(sep) |
text |
sep must be a literal |
group_concat(x [ORDER BY ...] [SEPARATOR s]) |
StringAgg(s) |
text | MySQL; default separator ,
|
json_agg(x), json_arrayagg(x)
|
JsonAgg |
json | |
jsonb_agg(x) |
JsonbAgg |
jsonb | |
json_object_agg(k, v), json_objectagg(k, v)
|
JsonObjectAgg |
json | |
jsonb_object_agg(k, v) |
JsonbObjectAgg |
jsonb | |
bool_and(x), every(x)
|
BoolAnd |
bool | |
bool_or(x) |
BoolOr |
bool | |
stddev(x), stddev_samp(x)
|
StddevSamp |
float8 | Needs two or more values, else NULL |
stddev_pop(x) |
StddevPop |
float8 | |
variance(x), var_samp(x)
|
VarSamp |
float8 | Needs two or more values, else NULL |
var_pop(x) |
VarPop |
float8 | |
mode() WITHIN GROUP (ORDER BY x) |
Mode |
text | |
percentile_cont(f) WITHIN GROUP (ORDER BY x) |
PercentileCont |
float8 | Linear interpolation |
percentile_disc(f) WITHIN GROUP (ORDER BY x) |
PercentileDisc |
float8 | Element at index ceil(f * n) - 1
|
ch_quantile_exact(f) WITHIN GROUP (ORDER BY x) |
QuantileExact |
float8 | Internal name for ClickHouse quantileExact; index floor(f * n)
|
grouping(a, ...), grouping_id(a, ...)
|
Grouping |
int4 | Bit mask of the grouping columns absent from the current grouping set |
(source: src/query/sql/parser.rs, parse_function_call; src/plan/logical.rs, AggregateFunc, AggregateFunc::is_extended; src/query/engine.rs, infer_expression_type aggregate arms, evaluate_aggregate, grouping_mask; src/query/aggregates.rs, compute_extended)
percentile_disc reports float8 for every input type, where PostgreSQL returns the input type. (source: src/query/engine.rs, infer_expression_type; src/plan/logical.rs, AggregateFunc::is_extended)
First, Last and Collect exist in AggregateFunc but are produced only by the MongoDB, SPARQL and Cypher planners, not by SQL. (source: src/query/mql/planner.rs; src/query/sparql/planner.rs; src/query/cypher/planner.rs)
In the MySQL dialect, sum of an exact integer type reports DECIMAL, and STD, STDDEV and VARIANCE are rewritten by parse_variance_family into expressions over SUM and COUNT. In the SQL Server dialect, sum of tinyint, smallint and int reports int. (source: src/query/engine.rs, infer_expression_type; src/query/sql/parser.rs, parse_variance_family)
Modifiers
| Modifier | Behaviour |
|---|---|
DISTINCT |
Values are de-duplicated by their text form before aggregation, so 1 and 1.0 count as two values |
FILTER (WHERE p) |
Only rows where p is true contribute |
ORDER BY inside the parentheses |
Sorts the inputs of array_agg, string_agg, group_concat and the JSON aggregates; several keys, ASC/DESC and NULLS FIRST/LAST are honoured |
WITHIN GROUP (ORDER BY x) |
Accepted only for mode, percentile_cont, percentile_disc and ch_quantile_exact; any other name raises Unsupported ordered-set aggregate
|
(source: src/query/engine.rs, evaluate_aggregate, collect_arg_values, collect_arg_values_ordered; src/query/sql/parser.rs, parse_function_call, parse_aggregate_filter)
Differences from PostgreSQL:
-
string_agg(x, sep)with a separator that is not a string literal (a column or parameter) uses,. (source:src/query/sql/parser.rs,parse_function_call) - In
WITHIN GROUP (ORDER BY ...)only the first sort expression is used and its direction is ignored. The fraction must be a literal; an array of fractions (percentile_cont(ARRAY[0.25, 0.5])) is not supported. (source:src/query/sql/parser.rs,parse_function_call,extended_fraction) -
stddev,varianceand the percentiles are computed inf64. The status notes record thatstddevover integers prints 15 significant digits where PostgreSQL prints 16, thatsumandavgoverfloat4differ in the last digits, and thatavg(numeric)prints 18 fractional digits where PostgreSQL prints 16. (source:src/query/aggregates.rs,compute_extended;docs/status/2026-11-30-pg-json-result-gaps.md) -
Not verified: an aggregate with both
FILTERandOVER(sum(x) FILTER (WHERE p) OVER (...)). The parser checks forOVERbeforeFILTER, and the window path does not carryDISTINCTorFILTER. (source:src/query/sql/parser.rs,parse_function_call)
How aggregates are evaluated
evaluate_aggregate receives the group's rows as text cells, applies FILTER, reads each argument through get_expr_value_from_row, and computes the result. sum and avg use exact decimal arithmetic for numeric input; the statistical functions call compute_extended. The result is returned as text and typed for the wire by infer_expression_type. (source: src/query/engine.rs, evaluate_aggregate; src/query/aggregates.rs, compute_extended)
Tested by unit tests percentiles_match_pg_and_clickhouse, variance, test_accumulator_count, test_accumulator_sum, test_accumulator_avg, test_accumulator_min_max and test_compare_values; by feature-matrix scenarios DML/count-distinct, agg-filter, string-agg-order, array-agg, sum-numeric, avg-numeric, avg-int, max-min, functions-json/json-agg, functions-json/jsonb-object-agg; and by the diff-corpus tag aggregate (22 queries) and the queries type_count, type_sum_int, type_avg, type_min_max, type_bool_agg, type_string_agg, type_array_agg, type_stddev and type_cte_agg. (source: src/query/aggregates.rs, tests; test-scripts/feature-matrix/features.py; test-scripts/diff/corpus.py)
GROUP BY
parse_group_by_clause turns the clause into a list of grouping sets. A plain GROUP BY a, b is one set.
| Form | Grouping sets produced |
|---|---|
GROUP BY a, b |
(a, b) |
GROUP BY ROLLUP (a, b) |
(a, b), (a), ()
|
GROUP BY CUBE (a, b) |
every subset of (a, b): (a, b), (a), (b), ()
|
GROUP BY GROUPING SETS ((a, b), (a), ()) |
exactly the sets listed |
MySQL GROUP BY a, b WITH ROLLUP
|
(a, b), (a), ()
|
GROUP BY (a, b) |
treated as GROUP BY a, b
|
GROUP BY 1, 2 |
select-list items by position |
Duplicate sets are removed. Columns missing from a set are NULL in that set's rows, and grouping() reports which ones are missing. (source: src/query/sql/parser.rs, parse_group_by_clause)
Difference from PostgreSQL: when plain expressions and a ROLLUP, CUBE or GROUPING SETS item are mixed, the parser adds each plain expression as its own singleton set (a union). PostgreSQL forms the cross product, so GROUP BY a, ROLLUP (b) means sets (a, b) and (a) in PostgreSQL but not here. A code comment in parse_group_by_clause states the union intent. (source: src/query/sql/parser.rs, parse_group_by_clause)
CUBE enumerates subsets with a 32-bit mask, so it accepts at most 31 elements. (source: same)
HAVING is evaluated per group after aggregation; aggregate calls inside it are looked up by the avg, sum, count, min and max arms of evaluate_row_expr against the computed group values. (source: src/query/engine.rs, evaluate_row_expr, avg | sum | count | min | max arm)
Tested by feature-matrix scenarios DML/rollup and DML/grouping-sets, and diff-corpus tag groupby (9 queries). No scenario exercises CUBE. Not verified: CUBE results. (source: test-scripts/feature-matrix/features.py; test-scripts/diff/corpus.py)
Window functions
A call followed by OVER (...) becomes Expr::Window { func, args, partition_by, order_by, frame }.
| SQL name | WindowFunc |
Result type | Notes |
|---|---|---|---|
row_number() |
RowNumber |
int8 | |
rank() |
Rank |
int8 | Peers share a rank; gaps follow |
dense_rank() |
DenseRank |
int8 | No gaps |
percent_rank() |
PercentRank |
float8 | (rank - 1) / (rows - 1) |
cume_dist() |
CumeDist |
float8 | Rows up to the last peer over partition size |
ntile(n) |
Ntile |
int4 (int8 in MySQL and SQL Server) | Extra rows go to the first buckets |
lag(x [, offset [, default]]), lead(...)
|
Lag, Lead
|
type of x
|
Offset counted in rows of the partition |
first_value(x), last_value(x), nth_value(x, n)
|
FirstValue, LastValue, NthValue
|
type of x
|
Use the frame |
any aggregate above with OVER
|
Aggregate(func) |
as the aggregate | Computed over the frame |
(source: src/query/sql/parser.rs, try_parse_window_function, parse_function_call; src/plan/logical.rs, WindowFunc; src/query/engine.rs, infer_expression_type, QueryEngine::evaluate_window_functions)
A window keyword written without parentheses (for example a column named rank) is read as a column. (source: src/query/sql/parser.rs, try_parse_window_function)
Window specification
parse_window_specification accepts PARTITION BY, ORDER BY and a frame. A named window (OVER w ... WINDOW w AS (...), including a window built on another named window) is inlined at the token level before parsing by resolve_named_windows. (source: src/query/sql/parser.rs, parse_window_specification, resolve_named_windows)
parse_window_frame accepts:
| Part | Accepted |
|---|---|
| Unit |
ROWS, RANGE, GROUPS
|
| Form |
BETWEEN start AND end, or a single start (end is CURRENT ROW) |
| Bounds |
UNBOUNDED PRECEDING, n PRECEDING, CURRENT ROW, n FOLLOWING, UNBOUNDED FOLLOWING
|
n |
Integer literal only |
EXCLUDE ..., interval offsets (RANGE INTERVAL '1 day' PRECEDING), IGNORE NULLS and RESPECT NULLS are not parsed. (source: src/query/sql/parser.rs, parse_window_frame, parse_frame_bound; src/plan/logical.rs, WindowFrame)
Execution
QueryEngine::evaluate_window_functions runs after the input rows are produced:
(source: src/query/engine.rs, QueryEngine::evaluate_window_functions)
Rules the executor applies:
- Sorting compares two values as numbers when both parse as
f64, otherwise as text. NULL sorts after non-NULL ascending, and the order is reversed forDESC. ExplicitNULLS FIRST/NULLS LASTin a windowORDER BYis not consulted. (source: same) - Default frame without
ORDER BY: the whole partition. Default frame withORDER BY: from the partition start to the last peer of the current row, which matches PostgreSQL'sRANGE BETWEEN UNBOUNDED PRECEDING AND CURRENT ROW. (source: same) - For
RANGEandGROUPS,CURRENT ROWextends to the current row's peers. A numericn PRECEDINGorn FOLLOWINGis applied as a row offset for all three units. In PostgreSQL,RANGE n PRECEDINGis a value offset andGROUPS n PRECEDINGcounts peer groups, so those frames give different results here. (source: same) - Aggregate windows over identical frame bounds are computed once and reused (
agg_memo); each frame is aggregated withevaluate_aggregate. In the MySQL dialect,SUMandAVGwindows over exact columns usewindow_exact_sum_avg. (source: same,window_exact_sum_avg)
Tested by feature-matrix scenarios DML/win-row-number, win-rank, win-dense-rank, win-lag, win-lead, win-running-sum, win-partition, win-frame-rows and win-ntile, and by diff-corpus tag window (9 queries) including type_window_funcs and type_window_sum. Not verified: RANGE and GROUPS frames with numeric offsets, percent_rank, cume_dist and nth_value; no scenario covers them. (source: test-scripts/feature-matrix/features.py; test-scripts/diff/corpus.py)
Unused window API
engine.rs also defines a public free function evaluate_window_functions with WindowFunctionType and WindowFunctionBuilder. Nothing outside the file calls them; SQL windows go through the method described above. Not wired: evaluate_window_functions (free function), WindowFunctionType, WindowFunctionBuilder. (source: src/query/engine.rs, free function evaluate_window_functions)