pg.ddx.io pgsql-hackers@postgresql.org mailing list archive
help / color / mirror / Atom feedON EMPTY clause for aggregate and window functions
14+ messages / 5 participants
[nested] [flat]
* ON EMPTY clause for aggregate and window functions
@ 2026-06-26 09:11 Jeevan Chalke <jeevan.chalke@enterprisedb.com>
0 siblings, 1 reply; 14+ messages in thread
From: Jeevan Chalke @ 2026-06-26 09:11 UTC (permalink / raw)
To: pgsql-hackers
Hello Hackers,
Here is a patch set adding an optional ON EMPTY clause to aggregate (and
aggregate-as-window-function) calls. It supplies a value to return when the
aggregate processes no input rows at all:
agg_function(args, default_value ON EMPTY)
For example:
SELECT sum(i, -1 ON EMPTY)
FROM generate_series(1,10) AS s(i) WHERE i > 100;
sum
-----
-1
(1 row)
ON EMPTY is triggered only by an empty input set, not by NULL inputs that
are
ignored during aggregation. A FILTER that removes all rows makes the input
set empty, so the default applies in that case too. Because a grouped query
never produces empty groups, ON EMPTY takes effect for an ungrouped
aggregate
over zero rows, or for a group whose rows are all removed by FILTER. For an
aggregate used as a window function, the default is returned for any row
whose
frame contains no rows. It also works with an ordered-set aggregate, with
the
default written before WITHIN GROUP:
percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY v)
ON EMPTY for aggregates is understood to be part of an upcoming revision of
the SQL standard.
The default_value must be a constant-like expression coercible to the
aggregate's result type: no column references (at any query level),
aggregates, window functions, subqueries, or volatile functions. It cannot
be combined with DISTINCT, and is rejected for non-aggregate window
functions.
*Implementation*: detection uses a per-group "input received" flag, set by a
dedicated expression step emitted after any FILTER but before the
strict-input
NULL check, so a NULL input still counts as input (a strict transition
function would otherwise skip it and an all-NULL group would be misread as
empty). At finalization, if the flag is unset, the default is evaluated and
returned in place of the normal result. Such aggregates are not partially
aggregated, since a parallel leader sees only combined transition states,
not
the original rows. The commit messages have the details.
*Patches*:
0001 - feature: grammar, parser, node support, planner, deparse, executor
(interpreter), documentation, and regression tests. Functional
without LLVM.
0002 - JIT support for the new expression step. 0001 and 0002 should be
applied together on --with-llvm builds; the split is only to make
the JIT part easy to review, and I'm happy to squash them. I have
limited expertise with the JIT code, so I'd appreciate help if
something
here is wrong.
make installcheck passes in both a --without-llvm build (interpreter) and a
--with-llvm build with jit = on (LLVM 17).
The current syntax is quite limited. Since there's no SQL standard for this
yet,
any feedback or suggestions on the syntax/grammar are very welcome.
Thanks,
--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*
enterprisedb.com <https://www.enterprisedb.com;
Attachments: download all (2 files, .tar.gz)
v1-0001-Add-support-for-ON-EMPTY-clause-in-aggregate-and-.patch (application/octet-stream, 71.1K) download
From 9cd400f11faad7289ad94672d5ea2f8357415845 Mon Sep 17 00:00:00 2001
From: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Date: Fri, 26 Jun 2026 12:54:24 +0530
Subject: [PATCH v1 1/2] Add support for ON EMPTY clause in aggregate and
window functions
This commit introduces the ON EMPTY clause, allowing users to specify
a default value to be returned when an aggregate or window function
receives an empty input set (zero processed rows). The syntax follows
the pattern:
agg_function(args, default_value ON EMPTY)
The ON EMPTY clause is distinct from standard NULL handling. It is
only invoked when the aggregate processes no rows at all. If the
aggregate processes rows that happen to be NULL, the normal transition
logic applies and the ON EMPTY clause is ignored. Likewise, when all
rows are removed by a FILTER clause the input set is empty and the
ON EMPTY value is returned. For a window aggregate, the default is
returned for any row whose frame contains no rows.
Implementation adds an 'inputReceived' flag to each per-group
aggregate state. A dedicated EEOP_AGG_INPUT_RECEIVED expression step
sets the flag once per row that reaches the aggregate -- after any
FILTER but before the strict-input NULL check -- so that a row whose
input is NULL (and is thus skipped by a strict transition function)
still counts as input. The step is emitted only for aggregates that
carry an ON EMPTY default. At finalization, if the flag is false,
the default expression is evaluated and returned in place of the
normal result (and final function, if any). Because a partial
aggregate's leader only sees workers' combined transition states
rather than the original rows, this flag cannot distinguish the
empty-input case under partial aggregation; such aggregates are
therefore marked non-partial so they are not parallelized.
This patch implements the new step in the expression interpreter only;
the feature is fully functional without LLVM. LLVM/JIT support for
the EEOP_AGG_INPUT_RECEIVED step is added by a separate follow-on
patch.
The default expression must be a constant-like expression coercible to
the aggregate's result type. It may not reference columns (at any
query level) or contain aggregates, window functions, subqueries, or
volatile functions. ON EMPTY cannot be combined with DISTINCT, and is
rejected for non-aggregate window functions; it may be used with an
ordered-set (WITHIN GROUP) aggregate, written before the WITHIN GROUP
clause.
Patch also includes documentation and regression tests for aggregates
and window functions, covering empty tables, filtered results, type
coercion, all-NULL inputs to strict aggregates, and view deparsing.
This commit adds fields to Aggref and WindowFunc (and FuncCall).
These node types are serialized into pg_rewrite (views/rules) and
other stored expression trees, which requires a CATALOG_VERSION_NO
bump. That is omitted here to avoid conflicts with concurrent
commits; the committer should bump it at commit time.
Proposed-by: Peter Eisentraut
Jeevan Chalke
---
doc/src/sgml/syntax.sgml | 46 +++
src/backend/executor/execExpr.c | 64 ++++
src/backend/executor/execExprInterp.c | 22 ++
src/backend/executor/nodeAgg.c | 32 ++
src/backend/executor/nodeWindowAgg.c | 41 ++
src/backend/nodes/makefuncs.c | 1 +
src/backend/nodes/nodeFuncs.c | 8 +
src/backend/optimizer/prep/prepagg.c | 12 +
src/backend/optimizer/util/clauses.c | 6 +
src/backend/parser/gram.y | 16 +
src/backend/parser/parse_agg.c | 134 ++++++-
src/backend/parser/parse_expr.c | 11 +-
src/backend/parser/parse_func.c | 37 +-
src/backend/utils/adt/ruleutils.c | 22 ++
src/include/executor/execExpr.h | 8 +
src/include/executor/nodeAgg.h | 10 +
src/include/nodes/parsenodes.h | 1 +
src/include/nodes/primnodes.h | 5 +
src/include/parser/parse_agg.h | 4 +-
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/aggregates.out | 463 +++++++++++++++++++++++
src/test/regress/expected/window.out | 108 ++++++
src/test/regress/sql/aggregates.sql | 198 ++++++++++
src/test/regress/sql/window.sql | 55 +++
24 files changed, 1297 insertions(+), 8 deletions(-)
diff --git a/doc/src/sgml/syntax.sgml b/doc/src/sgml/syntax.sgml
index 67482996861..d708a5ee484 100644
--- a/doc/src/sgml/syntax.sgml
+++ b/doc/src/sgml/syntax.sgml
@@ -1555,6 +1555,10 @@ sqrt(2)
<primary>FILTER</primary>
</indexterm>
+ <indexterm zone="syntax-aggregates">
+ <primary>ON EMPTY</primary>
+ </indexterm>
+
<para>
An <firstterm>aggregate expression</firstterm> represents the
application of an aggregate function across the rows selected by a
@@ -1564,6 +1568,7 @@ sqrt(2)
<synopsis>
<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
+<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] , <replaceable>default_expression</replaceable> ON EMPTY [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> ( * ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
@@ -1744,6 +1749,36 @@ FROM generate_series(1,10) AS s(i);
</programlisting>
</para>
+ <para>
+ If <literal>ON EMPTY</literal> is specified, then
+ <replaceable>default_expression</replaceable> supplies the value of the
+ aggregate when it processes no input rows at all; in that case the
+ aggregate's normal final result (and its final function, if any) is not
+ computed. This is distinct from null handling: it is triggered only by
+ an empty input set, not by null inputs that are merely ignored during
+ aggregation. Note that when rows exist but are all removed by a
+ <replaceable>filter_clause</replaceable>, the input set is empty and the
+ <literal>ON EMPTY</literal> value is returned. For example:
+<programlisting>
+SELECT sum(i) AS plain, sum(i, -1 ON EMPTY) AS defaulted
+FROM generate_series(1,10) AS s(i) WHERE i > 100;
+ plain | defaulted
+-------+-----------
+ | -1
+(1 row)
+</programlisting>
+ <replaceable>default_expression</replaceable> must be a constant-like
+ expression of a type coercible to the aggregate's result type: it may not
+ refer to columns or contain aggregates, window functions, subqueries, or
+ volatile functions. <literal>ON EMPTY</literal> cannot be combined with
+ <literal>DISTINCT</literal>. It may be used with an ordered-set
+ aggregate, written before the <literal>WITHIN GROUP</literal> clause.
+ Because a grouped query never produces empty groups,
+ <literal>ON EMPTY</literal> only takes effect for an ungrouped aggregate
+ over zero rows (or a group whose rows are all removed by
+ <replaceable>filter_clause</replaceable>).
+ </para>
+
<para>
The predefined aggregate functions are described in <xref
linkend="functions-aggregate"/>. Other aggregate functions can be added
@@ -1843,6 +1878,17 @@ EXCLUDE NO OTHERS
described in <xref linkend="functions-window"/>.
</para>
+ <para>
+ When an aggregate function is used as a window function, an
+ <literal>ON EMPTY</literal> clause may be given after its arguments
+ (using the same syntax as for a plain aggregate call, described in
+ <xref linkend="syntax-aggregates"/>). The
+ <replaceable>default_expression</replaceable> is then returned for any
+ row whose window frame contains no rows, including a frame that becomes
+ empty as the frame moves. <literal>ON EMPTY</literal> is not accepted for
+ non-aggregate window functions.
+ </para>
+
<para>
<replaceable>window_name</replaceable> is a reference to a named window
specification defined in the query's <literal>WINDOW</literal> clause.
diff --git a/src/backend/executor/execExpr.c b/src/backend/executor/execExpr.c
index cfea7e160c2..9a817eecb45 100644
--- a/src/backend/executor/execExpr.c
+++ b/src/backend/executor/execExpr.c
@@ -3736,6 +3736,70 @@ ExecBuildAggTrans(AggState *aggstate, AggStatePerPhase phase,
state->steps_len - 1);
}
+ /*
+ * If aggonempty present, emit step(s) to record that the group has
+ * received an input row. This is placed after any FILTER (so that
+ * filtered-out rows do not count as input) but before the
+ * strict-input NULL check emitted below (so that a row whose input is
+ * NULL still counts as input).
+ *
+ * The step is emitted once per concurrently-evaluated grouping set,
+ * mirroring the transition-function calls below. We skip it entirely
+ * for aggregates without ON EMPTY so the common case pays no
+ * overhead.
+ */
+ {
+ bool has_aggonempty = false;
+
+ for (int aggno = 0; aggno < aggstate->numaggs; aggno++)
+ {
+ if (aggstate->peragg[aggno].transno == transno &&
+ aggstate->peragg[aggno].aggref->aggonempty != NULL)
+ {
+ has_aggonempty = true;
+ break;
+ }
+ }
+
+ if (has_aggonempty)
+ {
+ scratch.opcode = EEOP_AGG_INPUT_RECEIVED;
+ scratch.d.agg_input_received.transno = transno;
+
+ if (doSort)
+ {
+ int processGroupingSets = Max(phase->numsets, 1);
+ int setoff = 0;
+
+ for (int setno = 0; setno < processGroupingSets; setno++)
+ {
+ scratch.d.agg_input_received.setoff = setoff;
+ ExprEvalPushStep(state, &scratch);
+ setoff++;
+ }
+ }
+
+ if (doHash)
+ {
+ int numHashes = aggstate->num_hashes;
+ int setoff;
+
+ /* in MIXED mode, there'll be preceding transition values */
+ if (aggstate->aggstrategy != AGG_HASHED)
+ setoff = aggstate->maxsets;
+ else
+ setoff = 0;
+
+ for (int setno = 0; setno < numHashes; setno++)
+ {
+ scratch.d.agg_input_received.setoff = setoff;
+ ExprEvalPushStep(state, &scratch);
+ setoff++;
+ }
+ }
+ }
+ }
+
/*
* Evaluate arguments to aggregate/combine function.
*/
diff --git a/src/backend/executor/execExprInterp.c b/src/backend/executor/execExprInterp.c
index 0634af964a9..2df5722ddba 100644
--- a/src/backend/executor/execExprInterp.c
+++ b/src/backend/executor/execExprInterp.c
@@ -592,6 +592,7 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
&&CASE_EEOP_AGG_STRICT_INPUT_CHECK_ARGS_1,
&&CASE_EEOP_AGG_STRICT_INPUT_CHECK_NULLS,
&&CASE_EEOP_AGG_PLAIN_PERGROUP_NULLCHECK,
+ &&CASE_EEOP_AGG_INPUT_RECEIVED,
&&CASE_EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL,
&&CASE_EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL,
&&CASE_EEOP_AGG_PLAIN_TRANS_BYVAL,
@@ -2106,6 +2107,27 @@ ExecInterpExpr(ExprState *state, ExprContext *econtext, bool *isnull)
EEO_NEXT();
}
+ /*
+ * Mark that an aggregate's per-group state has received an input row
+ * (used by the ON EMPTY clause). This is emitted once per row that
+ * reaches the aggregate, after any FILTER but before the strict-input
+ * NULL check, so that a row whose input is NULL still counts as
+ * input. Only emitted for aggregates that actually carry an ON EMPTY
+ * default.
+ */
+ EEO_CASE(EEOP_AGG_INPUT_RECEIVED)
+ {
+ AggState *aggstate = castNode(AggState, state->parent);
+ AggStatePerGroup pergroup_allaggs =
+ aggstate->all_pergroups[op->d.agg_input_received.setoff];
+
+ /* pergroup may be NULL in the hashed/spilled case; just skip */
+ if (pergroup_allaggs != NULL)
+ pergroup_allaggs[op->d.agg_input_received.transno].inputReceived = true;
+
+ EEO_NEXT();
+ }
+
/*
* Different types of aggregate transition functions are implemented
* as different types of steps, to avoid incurring unnecessary
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 925caadd2ce..fed8fc33710 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -649,6 +649,12 @@ initialize_aggregate(AggState *aggstate, AggStatePerTrans pertrans,
* still need to do this.
*/
pergroupstate->noTransValue = pertrans->initValueIsNull;
+
+ /*
+ * Initialize the flag used for ON EMPTY to track whether any input rows
+ * were received.
+ */
+ pergroupstate->inputReceived = false;
}
/*
@@ -1057,6 +1063,25 @@ finalize_aggregate(AggState *aggstate,
oldContext = MemoryContextSwitchTo(aggstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory);
+ /*
+ * If the ON EMPTY clause is specified with a default value, evaluate and
+ * return it in cases where no input rows were received.
+ *
+ * The inputReceived flag is used to detect the empty set case (zero rows
+ * processed).
+ */
+ if (peragg->aggonemptystate != NULL && !pergroupstate->inputReceived)
+ {
+ *resultVal = ExecEvalExpr(peragg->aggonemptystate,
+ aggstate->ss.ps.ps_ExprContext,
+ resultIsNull);
+
+ /* Switch back to the caller's context before returning */
+ MemoryContextSwitchTo(oldContext);
+
+ return;
+ }
+
/*
* Evaluate any direct arguments. We do this even if there's no finalfn
* (which is unlikely anyway), so that side-effects happen as expected.
@@ -3959,6 +3984,13 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
get_func_name(transfn_oid));
InvokeFunctionExecuteHook(transfn_oid);
+ /* Build expression state for ON EMPTY default expression */
+ if (aggref->aggonempty)
+ peragg->aggonemptystate = ExecInitExpr(aggref->aggonempty,
+ (PlanState *) aggstate);
+ else
+ peragg->aggonemptystate = NULL;
+
/*
* initval is potentially null, so don't try to access it as a
* struct field. Must do it the hard way with SysCacheGetAttr.
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index f1c524d00df..2a943d0a93b 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -172,6 +172,12 @@ typedef struct WindowStatePerAggData
/* Data local to eval_windowaggregates() */
bool restart; /* need to restart this agg in this cycle? */
+
+ /* ON EMPTY support */
+ bool inputReceived; /* true if any input row was received in
+ * current frame */
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} WindowStatePerAggData;
static void initialize_windowaggregate(WindowAggState *winstate,
@@ -279,6 +285,12 @@ initialize_windowaggregate(WindowAggState *winstate,
peraggstate->transValueCount = 0;
peraggstate->resultValue = (Datum) 0;
peraggstate->resultValueIsNull = true;
+
+ /*
+ * Initialize the flag used for ON EMPTY to track whether any input rows
+ * were received in this frame.
+ */
+ peraggstate->inputReceived = false;
}
/*
@@ -326,6 +338,9 @@ advance_windowaggregate(WindowAggState *winstate,
i++;
}
+ /* Mark that this aggregate received input (used for ON EMPTY) */
+ peraggstate->inputReceived = true;
+
if (peraggstate->transfn.fn_strict)
{
/*
@@ -635,6 +650,25 @@ finalize_windowaggregate(WindowAggState *winstate,
oldContext = MemoryContextSwitchTo(winstate->ss.ps.ps_ExprContext->ecxt_per_tuple_memory);
+ /*
+ * If the ON EMPTY clause is specified with a default value, evaluate and
+ * return it in cases where no input rows were received in the current
+ * frame.
+ *
+ * The inputReceived flag is used to detect the empty frame case (zero
+ * rows processed in this frame).
+ */
+ if (peraggstate->aggonemptystate != NULL && !peraggstate->inputReceived)
+ {
+ *result = ExecEvalExpr(peraggstate->aggonemptystate,
+ winstate->ss.ps.ps_ExprContext,
+ isnull);
+
+ MemoryContextSwitchTo(oldContext);
+
+ return;
+ }
+
/*
* Apply the agg's finalfn if one is provided, else return transValue.
*/
@@ -3135,6 +3169,13 @@ initialize_peragg(WindowAggState *winstate, WindowFunc *wfunc,
&peraggstate->transtypeLen,
&peraggstate->transtypeByVal);
+ /* Build expression state for ON EMPTY default expression */
+ if (wfunc->aggonempty)
+ peraggstate->aggonemptystate = ExecInitExpr(wfunc->aggonempty,
+ (PlanState *) winstate);
+ else
+ peraggstate->aggonemptystate = NULL;
+
/*
* initval is potentially null, so don't try to access it as a struct
* field. Must do it the hard way with SysCacheGetAttr.
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index 40b09958ac2..f76a5d3a491 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -681,6 +681,7 @@ makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
n->args = args;
n->agg_order = NIL;
n->agg_filter = NULL;
+ n->agg_on_empty = NULL;
n->over = NULL;
n->agg_within_group = false;
n->agg_star = false;
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 2a2e00b372e..c6e50979350 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -2168,6 +2168,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
}
break;
case T_GroupingFunc:
@@ -2187,6 +2189,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
if (WALK(expr->runCondition))
return true;
}
@@ -3101,6 +3105,7 @@ expression_tree_mutator_impl(Node *node,
MUTATE(newnode->aggorder, aggref->aggorder, List *);
MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
MUTATE(newnode->aggfilter, aggref->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, aggref->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -3135,6 +3140,7 @@ expression_tree_mutator_impl(Node *node,
FLATCOPY(newnode, wfunc, WindowFunc);
MUTATE(newnode->args, wfunc->args, List *);
MUTATE(newnode->aggfilter, wfunc->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, wfunc->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -4532,6 +4538,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(fcall->agg_filter))
return true;
+ if (WALK(fcall->agg_on_empty))
+ return true;
if (WALK(fcall->over))
return true;
/* function name is deemed uninteresting */
diff --git a/src/backend/optimizer/prep/prepagg.c b/src/backend/optimizer/prep/prepagg.c
index 3737cc15ba1..cc16bc4edeb 100644
--- a/src/backend/optimizer/prep/prepagg.c
+++ b/src/backend/optimizer/prep/prepagg.c
@@ -215,6 +215,18 @@ preprocess_aggref(Aggref *aggref, PlannerInfo *root)
ReleaseSysCache(aggTuple);
+ /*
+ * An ON EMPTY default is returned only when the aggregate processes zero
+ * input rows, which is detected via a per-group "input received" flag set
+ * as the aggregate's input rows are processed. Under partial aggregation
+ * the leader sees only the workers' combined partial states (via the
+ * combine function), not the original rows, so that flag cannot reliably
+ * distinguish the empty-input case. Disable partial aggregation for such
+ * aggregates.
+ */
+ if (aggref->aggonempty != NULL)
+ root->hasNonPartialAggs = true;
+
/*
* 1. See if this is identical to another aggregate function call that
* we've seen already.
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 01997e22266..a3df2b451a6 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -2777,6 +2777,7 @@ eval_const_expressions_mutator(Node *node,
Oid funcid = expr->winfnoid;
List *args;
Expr *aggfilter;
+ Expr *aggonempty;
HeapTuple func_tuple;
WindowFunc *newexpr;
@@ -2806,6 +2807,10 @@ eval_const_expressions_mutator(Node *node,
aggfilter = (Expr *)
eval_const_expressions_mutator((Node *) expr->aggfilter,
context);
+ /* ... and the ON EMPTY expression */
+ aggonempty = (Expr *)
+ eval_const_expressions_mutator((Node *) expr->aggonempty,
+ context);
/* And build the replacement WindowFunc node */
newexpr = makeNode(WindowFunc);
@@ -2815,6 +2820,7 @@ eval_const_expressions_mutator(Node *node,
newexpr->inputcollid = expr->inputcollid;
newexpr->args = args;
newexpr->aggfilter = aggfilter;
+ newexpr->aggonempty = aggonempty;
newexpr->runCondition = expr->runCondition;
newexpr->winref = expr->winref;
newexpr->winstar = expr->winstar;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index ff4e1388c55..52271b010c0 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -467,6 +467,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <list> group_by_list
%type <node> group_by_item empty_grouping_set rollup_clause cube_clause
%type <node> grouping_sets_clause
+%type <node> on_empty
%type <list> opt_fdw_options fdw_options
%type <defelt> fdw_option
@@ -16590,6 +16591,16 @@ func_application: func_name '(' ')'
n->agg_order = $7;
$$ = (Node *) n;
}
+ | func_name '(' func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $3,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $5;
+ n->agg_order = $6;
+ $$ = (Node *) n;
+ }
| func_name '(' ALL func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16635,6 +16646,11 @@ func_application: func_name '(' ')'
;
+on_empty: a_expr ON EMPTY_P
+ { $$ = $1; }
+ ;
+
+
/*
* func_expr and its cousin func_expr_windowless are split out from c_expr just
* so that we have classifications for "everything that is a function call or
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index acb933392de..9479a1a03b3 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -21,6 +21,7 @@
#include "common/int.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
+#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
@@ -82,6 +83,9 @@ static Var *buildGroupedVar(int attnum, Index ressortgroupref,
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
static List *expand_groupingset_node(GroupingSet *gs);
static Node *make_agg_arg(Oid argtype, Oid argcollation);
+static Node *check_agg_on_empty(ParseState *pstate, Oid aggtype,
+ Expr *agg_on_empty, int location);
+static bool agg_on_empty_contains_var_walker(Node *node, void *context);
/*
@@ -111,7 +115,8 @@ static Node *make_agg_arg(Oid argtype, Oid argcollation);
*/
void
transformAggregateCall(ParseState *pstate, Aggref *agg,
- List *args, List *aggorder, bool agg_distinct)
+ List *args, List *aggorder, bool agg_distinct,
+ Expr *agg_on_empty)
{
List *argtypes = NIL;
List *tlist = NIL;
@@ -231,6 +236,8 @@ transformAggregateCall(ParseState *pstate, Aggref *agg,
agg->args = tlist;
agg->aggorder = torder;
agg->aggdistinct = tdistinct;
+ agg->aggonempty = (Expr *) check_agg_on_empty(pstate, agg->aggtype,
+ agg_on_empty, agg->location);
/*
* Now build the aggargtypes list with the type OIDs of the direct and
@@ -499,6 +506,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
else
err = _("grouping operations are not allowed in DEFAULT expressions");
+ break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+
+ if (isAgg)
+ err = _("aggregate functions are not allowed in ON EMPTY expressions");
+ else
+ err = _("grouping operations are not allowed in ON EMPTY expressions");
+
break;
case EXPR_KIND_INDEX_EXPRESSION:
if (isAgg)
@@ -892,7 +907,7 @@ check_agg_arguments_walker(Node *node,
*/
void
transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef)
+ WindowDef *windef, Expr *agg_on_empty)
{
const char *err;
bool errkind;
@@ -1003,6 +1018,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("window functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("window functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("window functions are not allowed in index expressions");
break;
@@ -1140,6 +1158,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
}
pstate->p_hasWindowFuncs = true;
+ wfunc->aggonempty = (Expr *) check_agg_on_empty(pstate, wfunc->wintype,
+ agg_on_empty,
+ wfunc->location);
}
/*
@@ -2408,3 +2429,112 @@ make_agg_arg(Oid argtype, Oid argcollation)
argp->location = -1;
return (Node *) argp;
}
+
+/*
+ * check_agg_on_empty -
+ * Checks the aggregate's ON EMPTY expression for correctness.
+ */
+static Node *
+check_agg_on_empty(ParseState *pstate, Oid aggtype, Expr *agg_on_empty,
+ int location)
+{
+ Oid defexprtype;
+
+ if (!agg_on_empty)
+ return NULL;
+
+ /*
+ * default expression must be a constant - it cannot contain column
+ * references (Var nodes), aggregates, or window functions.
+ *
+ * Note we cannot use contain_var_clause() here: it only detects Vars of
+ * the current query level, so a correlated reference to an outer query's
+ * column (varlevelsup > 0) would slip through and make the "constant"
+ * default vary per outer row. Reject Vars of any level.
+ */
+ if (agg_on_empty_contains_var_walker((Node *) agg_on_empty, NULL))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must be a constant value"),
+ parser_errposition(pstate, location)));
+
+ if (contain_agg_clause((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain an aggregate function"),
+ parser_errposition(pstate, location)));
+
+ if (contain_windowfuncs((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a window function"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * Sub-selects are not constant and, more importantly, the ON EMPTY
+ * expression is only run through ExecInitExpr() at execution time, never
+ * the sub-plan setup that a normal target expression receives, so a
+ * sub-select here would fail (or crash) at execution. Reject it.
+ */
+ if (checkExprHasSubLink((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a subquery"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * The default is evaluated only once, for the empty-input case, so a
+ * volatile expression would not behave like a per-row value. Restrict it
+ * to a stable/immutable, constant-like expression.
+ */
+ if (contain_volatile_functions((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a volatile function"),
+ parser_errposition(pstate, location)));
+
+ defexprtype = exprType((Node *) agg_on_empty);
+
+ /* default expression must be coercible to the aggregate's result type. */
+ agg_on_empty = (Expr *) coerce_to_target_type(pstate,
+ (Node *) agg_on_empty,
+ defexprtype,
+ aggtype,
+ -1,
+ COERCION_ASSIGNMENT,
+ COERCE_IMPLICIT_CAST,
+ -1);
+
+ if (agg_on_empty == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("ON EMPTY expression type %s cannot be coerced to aggregate result type %s",
+ format_type_be(defexprtype),
+ format_type_be(aggtype)),
+ parser_errposition(pstate, location)));
+
+ return (Node *) agg_on_empty;
+}
+
+/*
+ * agg_on_empty_contains_var_walker -
+ * Returns true if the node tree contains any Var (a column reference) or
+ * CurrentOfExpr, regardless of query level.
+ *
+ * Unlike contain_var_clause(), this also reports Vars belonging to outer
+ * query levels (varlevelsup > 0), which is what we need to ensure an ON EMPTY
+ * default really is constant. Sub-selects are rejected separately, so there
+ * is no need to descend into them here. This runs during parse analysis, so
+ * PlaceHolderVars (which the planner introduces) cannot appear; a Var inside
+ * one would be caught by the recursion anyway.
+ */
+static bool
+agg_on_empty_contains_var_walker(Node *node, void *context)
+{
+ if (node == NULL)
+ return false;
+ if (IsA(node, Var) || IsA(node, CurrentOfExpr))
+ return true;
+ return expression_tree_walker(node, agg_on_empty_contains_var_walker,
+ context);
+}
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 9adc9d4c0f6..add73b52580 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -567,6 +567,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_CHECK_CONSTRAINT:
case EXPR_KIND_DOMAIN_CHECK:
case EXPR_KIND_FUNCTION_DEFAULT:
+ case EXPR_KIND_AGG_ON_EMPTY:
case EXPR_KIND_INDEX_EXPRESSION:
case EXPR_KIND_INDEX_PREDICATE:
case EXPR_KIND_STATS_EXPRESSION:
@@ -1853,6 +1854,9 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("cannot use subquery in DEFAULT expression");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("cannot use subquery in ON EMPTY expression");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("cannot use subquery in index expression");
break;
@@ -3227,6 +3231,8 @@ ParseExprKindName(ParseExprKind exprKind)
case EXPR_KIND_COLUMN_DEFAULT:
case EXPR_KIND_FUNCTION_DEFAULT:
return "DEFAULT";
+ case EXPR_KIND_AGG_ON_EMPTY:
+ return "ON EMPTY";
case EXPR_KIND_INDEX_EXPRESSION:
return "index expression";
case EXPR_KIND_INDEX_PREDICATE:
@@ -3991,7 +3997,7 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
parser_errposition(pstate, agg_ctor->location));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, agg_ctor->over);
+ transformWindowFuncCall(pstate, wfunc, agg_ctor->over, NULL);
node = (Node *) wfunc;
}
@@ -4018,7 +4024,8 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
aggref->aggtransno = -1;
aggref->location = agg_ctor->location;
- transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order, false);
+ transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order,
+ false, NULL);
node = (Node *) aggref;
}
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index fb306c05112..c9aa8baa2ff 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -95,6 +95,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
Expr *agg_filter = NULL;
+ Expr *agg_on_empty = NULL;
WindowDef *over = (fn ? fn->over : NULL);
bool agg_within_group = (fn ? fn->agg_within_group : false);
bool agg_star = (fn ? fn->agg_star : false);
@@ -130,6 +131,15 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
EXPR_KIND_FILTER,
"FILTER");
+ /*
+ * If there's an aggregate ON EMPTY default value given, transform it
+ * here. It is parsed in its own expression kind so that disallowed
+ * constructs are reported as occurring "in ON EMPTY expressions".
+ */
+ if (fn && fn->agg_on_empty != NULL)
+ agg_on_empty = (Expr *) transformExpr(pstate, fn->agg_on_empty,
+ EXPR_KIND_AGG_ON_EMPTY);
+
/*
* Most of the rest of the parser just assumes that functions do not have
* more than FUNC_MAX_ARGS parameters. We have to test here to protect
@@ -226,6 +236,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
*/
could_be_projection = (nargs == 1 && !proc_call &&
agg_order == NIL && agg_filter == NULL &&
+ agg_on_empty == NULL &&
!agg_star && !agg_distinct && over == NULL &&
!func_variadic && argnames == NIL &&
list_length(funcname) == 1 &&
@@ -339,6 +350,12 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("ORDER BY specified, but %s is not an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+ if (agg_on_empty != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("ON EMPTY specified, but %s is not an aggregate function",
+ NameListToString(funcname)),
+ parser_errposition(pstate, location)));
if (agg_filter)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
@@ -835,7 +852,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional aggregate-specific processing */
- transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
+ transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct,
+ agg_on_empty);
retval = (Node *) aggref;
}
@@ -897,6 +915,18 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("FILTER is not implemented for non-aggregate window functions"),
parser_errposition(pstate, location)));
+ /*
+ * ON EMPTY only has meaning for aggregates: it supplies the value to
+ * return when the aggregate processes no rows. A true window
+ * function does not aggregate input rows, so it would be silently
+ * ignored; reject it instead.
+ */
+ if (!wfunc->winagg && agg_on_empty)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("ON EMPTY is not implemented for non-aggregate window functions"),
+ parser_errposition(pstate, location)));
+
/*
* Window functions can't either take or return sets
*/
@@ -915,7 +945,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, over);
+ transformWindowFuncCall(pstate, wfunc, over, agg_on_empty);
retval = (Node *) wfunc;
}
@@ -2755,6 +2785,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("set-returning functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("set-returning functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("set-returning functions are not allowed in index expressions");
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 88de5c0481c..81da620f461 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -11524,6 +11524,14 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
*/
Assert(!aggref->aggvariadic);
get_rule_expr((Node *) aggref->aggdirectargs, context, true);
+
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
Assert(aggref->aggorder != NIL);
appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
get_rule_orderby(aggref->aggorder, aggref->args, false, context);
@@ -11569,6 +11577,13 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
}
}
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (aggref->aggorder != NIL)
{
appendStringInfoString(buf, " ORDER BY ");
@@ -11669,6 +11684,13 @@ get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
get_rule_expr((Node *) wfunc->args, context, true);
}
+ if (wfunc->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) wfunc->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (options)
appendStringInfoString(buf, options);
diff --git a/src/include/executor/execExpr.h b/src/include/executor/execExpr.h
index c61b3d624d5..ac95dd78316 100644
--- a/src/include/executor/execExpr.h
+++ b/src/include/executor/execExpr.h
@@ -281,6 +281,7 @@ typedef enum ExprEvalOp
EEOP_AGG_STRICT_INPUT_CHECK_ARGS_1,
EEOP_AGG_STRICT_INPUT_CHECK_NULLS,
EEOP_AGG_PLAIN_PERGROUP_NULLCHECK,
+ EEOP_AGG_INPUT_RECEIVED,
EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL,
EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL,
EEOP_AGG_PLAIN_TRANS_BYVAL,
@@ -729,6 +730,13 @@ typedef struct ExprEvalStep
int jumpnull;
} agg_plain_pergroup_nullcheck;
+ /* for EEOP_AGG_INPUT_RECEIVED */
+ struct
+ {
+ int setoff;
+ int transno;
+ } agg_input_received;
+
/* for EEOP_AGG_PRESORTED_DISTINCT_{SINGLE,MULTI} */
struct
{
diff --git a/src/include/executor/nodeAgg.h b/src/include/executor/nodeAgg.h
index 1e1be9666ae..377fac40494 100644
--- a/src/include/executor/nodeAgg.h
+++ b/src/include/executor/nodeAgg.h
@@ -229,6 +229,9 @@ typedef struct AggStatePerAggData
* aggregates because the final function is read-write.
*/
bool shareable;
+
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} AggStatePerAggData;
/*
@@ -264,6 +267,13 @@ typedef struct AggStatePerGroupData
* NULL and not auto-replace it with a later input value. Only the first
* non-NULL input will be auto-substituted.
*/
+
+ /*
+ * Whether this group has seen any input row yet. Used by the ON EMPTY
+ * clause to detect the empty-input case at finalization.
+ */
+#define FIELDNO_AGGSTATEPERGROUPDATA_INPUTRECEIVED 3
+ bool inputReceived;
} AggStatePerGroupData;
/*
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 4133c404a6b..925f2ed7f64 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -462,6 +462,7 @@ typedef struct FuncCall
bool agg_within_group; /* ORDER BY appeared in WITHIN GROUP */
bool agg_star; /* argument was really '*' */
bool agg_distinct; /* arguments were labeled DISTINCT */
+ Node *agg_on_empty; /* user given value to use ON EMPTY set */
bool func_variadic; /* last argument was labeled VARIADIC */
CoercionForm funcformat; /* how to display this node */
ParseLoc location; /* token location, or -1 if unknown */
diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h
index bb05aeebee4..930d9eac6d3 100644
--- a/src/include/nodes/primnodes.h
+++ b/src/include/nodes/primnodes.h
@@ -493,6 +493,9 @@ typedef struct Aggref
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
+
/* true if argument list was really '*' */
bool aggstar pg_node_attr(query_jumble_ignore);
@@ -598,6 +601,8 @@ typedef struct WindowFunc
List *args;
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
/* List of WindowFuncRunConditions to help short-circuit execution */
List *runCondition pg_node_attr(query_jumble_ignore);
/* index of associated WindowClause */
diff --git a/src/include/parser/parse_agg.h b/src/include/parser/parse_agg.h
index 8a5653798db..f93e956b83e 100644
--- a/src/include/parser/parse_agg.h
+++ b/src/include/parser/parse_agg.h
@@ -17,12 +17,12 @@
extern void transformAggregateCall(ParseState *pstate, Aggref *agg,
List *args, List *aggorder,
- bool agg_distinct);
+ bool agg_distinct, Expr *agg_on_empty);
extern Node *transformGroupingFunc(ParseState *pstate, GroupingFunc *p);
extern void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef);
+ WindowDef *windef, Expr *agg_on_empty);
extern void parseCheckAggregates(ParseState *pstate, Query *qry);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f7f4ba6c2a8..00a6b6f9f00 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -70,6 +70,7 @@ typedef enum ParseExprKind
EXPR_KIND_DOMAIN_CHECK, /* CHECK constraint for a domain */
EXPR_KIND_COLUMN_DEFAULT, /* default value for a table column */
EXPR_KIND_FUNCTION_DEFAULT, /* default parameter value for function */
+ EXPR_KIND_AGG_ON_EMPTY, /* aggregate/window ON EMPTY default value */
EXPR_KIND_INDEX_EXPRESSION, /* index expression */
EXPR_KIND_INDEX_PREDICATE, /* index predicate */
EXPR_KIND_STATS_EXPRESSION, /* extended statistics expression */
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 89e051ee824..a9c5315bc52 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -3983,3 +3983,466 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+-- Test ON EMPTY clause for aggregates
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+ sum
+-----
+ -1
+(1 row)
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ -1
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+ 0
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ max
+-----
+ 999
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ min
+------
+ -999
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ count
+-------
+ 0
+(1 row)
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum
+-----
+ 30
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ max
+-----
+ 20
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ min
+-----
+ 10
+(1 row)
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+ NONE
+(1 row)
+
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ string_agg
+------------
+ 10,10
+(1 row)
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+
+(1 row)
+
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+
+(1 row)
+
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+
+(1 row)
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 1
+(1 row)
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- with GROUP BY and empty groups
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+ g | sum
+-----+-----
+ 10 | 30
+ 20 | 30
+ 100 |
+ 200 |
+(4 rows)
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+ | 110
+(4 rows)
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+RESET enable_sort;
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+ grpid | parity | s
+-------+--------+----
+ 10 | 0 | -1
+ 10 | 1 | -1
+ 10 | | -1
+ 20 | 0 | -1
+ 20 | 1 | 30
+ 20 | | 30
+ 30 | 1 | 50
+ 30 | | 50
+ | 0 | -1
+ | 1 | 80
+ | | 80
+(11 rows)
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ sum
+-----
+ 100
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ count
+-------
+ 0
+(1 row)
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+ avg
+------
+ -999
+(1 row)
+
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+-- under a forced parallel plan: ON EMPTY must work whether or not the
+-- aggregate is parallelized (such aggregates are not partially aggregated).
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+ sum
+-----
+ -1
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+ sum
+-----
+ 30
+(1 row)
+
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+-- Error cases for ON EMPTY
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must be a constant value
+LINE 1: SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid ...
+ ^
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: invalid input syntax for type bigint: "invalid"
+LINE 1: SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE ...
+ ^
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+ERROR: ON EMPTY specified, but length is not an aggregate function
+LINE 1: SELECT length('test', 'default' ON EMPTY);
+ ^
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: cannot use subquery in ON EMPTY expression
+LINE 1: SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE...
+ ^
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must not contain a volatile function
+LINE 1: SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WH...
+ ^
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: set-returning functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_...
+ ^
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: aggregate functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE g...
+ ^
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: window functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_e...
+ ^
+-- combined with DISTINCT (should fail - not supported by the grammar)
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: syntax error at or near "ON"
+LINE 1: SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE...
+ ^
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+ percentile_cont
+-----------------
+ 15
+(1 row)
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+ pg_get_viewdef
+---------------------------------------------------------------------------------------------------------------------------------
+ SELECT percentile_cont((0.5)::double precision, '-7'::integer ON EMPTY) WITHIN GROUP (ORDER BY ((val)::double precision)) AS p+
+ FROM agg_on_empty;
+(1 row)
+
+DROP VIEW agg_on_empty_os_vw;
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+\d+ agg_on_empty_vw
+ View "public.agg_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+---------+---------+-----------+----------+---------+---------+-------------
+ grpid | integer | | | | plain |
+ total | bigint | | | | plain |
+ average | numeric | | | | main |
+ cnt | bigint | | | | plain |
+View definition:
+ SELECT grpid,
+ sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average,
+ count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty
+ GROUP BY grpid;
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+ grpid | total | average | cnt
+-------+-------+---------------------+-----
+ 10 | 30 | 15.0000000000000000 | 2
+ 20 | 30 | 30.0000000000000000 | 1
+ 30 | 50 | 50.0000000000000000 | 1
+(3 rows)
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+EXECUTE on_empty_test(40);
+ sum
+-----
+ 42
+(1 row)
+
+EXECUTE on_empty_test(10);
+ sum
+-----
+ 30
+(1 row)
+
+DEALLOCATE on_empty_test;
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+ grpid | total
+-------+-------
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- ON EMPTY must NOT fire for a non-empty group whose rows are all NULL: such
+-- a group has processed rows, so the normal (NULL) result applies. This is
+-- exercised against a strict transition function (max/min/sum of int are
+-- handled differently, so test a strict one explicitly) and across the
+-- sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+-- strict transition function (max/min) over an all-NULL, non-empty group
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- NULL, not -1
+ max
+-----
+
+(1 row)
+
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- NULL, not -1
+ min
+-----
+
+(1 row)
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 |
+(4 rows)
+
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 |
+(4 rows)
+
+RESET enable_sort; RESET enable_hashagg;
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 |
+ | 50
+(5 rows)
+
+-- a strict ordered-set aggregate over an all-NULL group also processes rows,
+-- so ON EMPTY is not used (NULL); a truly empty input still uses it
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- NULL
+ percentile_cont
+-----------------
+
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+-- the all-NULL behavior is the same for a window aggregate, which uses ON
+-- EMPTY only for a row whose frame contains no rows
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+ val | m
+-----+---
+ |
+ |
+(2 rows)
+
+-- ON EMPTY must be a constant: a correlated reference to an outer query's
+-- column is not constant and must be rejected (it is not caught by a
+-- current-level-only Var check)
+SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10;
+ERROR: ON EMPTY expression must be a constant value
+LINE 1: SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ ^
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index 90d9f953b81..c685757e410 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -6046,3 +6046,111 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
NOTICE: drop cascades to view planets_view
+-- Test ON EMPTY clause with window functions
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 |
+(5 rows)
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | 50
+ 2 | 20 | 30
+ 3 | 30 | 50
+ 4 | | 50
+ 5 | 50 | -222
+(5 rows)
+
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | -222
+ 2 | 20 | 10
+ 3 | 30 | 30
+ 4 | | 50
+ 5 | 50 | 30
+(5 rows)
+
+-- Frames with only NULL values (ON EMPTY value WILL NOT be returned)
+-- Row 4 has NULL, when frame contains only that row, should NOT return ON EMPTY value
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+ id | val | sum_current | avg_current
+----+-----+-------------+-------------
+ 4 | | |
+(1 row)
+
+-- Partition with only NULL values (ON EMPTY value WILL NOT be returned)
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+ grpid | id | val | sum_nulls | avg_nulls | max_nulls
+-------+----+-----+-----------+-----------+-----------
+ 40 | 6 | | | |
+ 40 | 7 | | | |
+(2 rows)
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+\d+ win_on_empty_vw
+ View "public.win_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+--------------+---------+-----------+----------+---------+---------+-------------
+ id | integer | | | | plain |
+ val | integer | | | | plain |
+ sum_prev_row | bigint | | | | plain |
+View definition:
+ SELECT id,
+ val,
+ sum(val, '-111'::integer ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty
+ ORDER BY id;
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 |
+ 6 | | 50
+ 7 | |
+(7 rows)
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+ERROR: ON EMPTY is not implemented for non-aggregate window functions
+LINE 1: SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_o...
+ ^
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 916383db927..78a595e1354 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -1798,3 +1798,201 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+
+
+-- Test ON EMPTY clause for aggregates
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+
+-- with GROUP BY and empty groups
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+RESET enable_sort;
+
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+
+-- under a forced parallel plan: ON EMPTY must work whether or not the
+-- aggregate is parallelized (such aggregates are not partially aggregated).
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+
+-- Error cases for ON EMPTY
+
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- combined with DISTINCT (should fail - not supported by the grammar)
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+DROP VIEW agg_on_empty_os_vw;
+
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+
+\d+ agg_on_empty_vw
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+
+EXECUTE on_empty_test(40);
+EXECUTE on_empty_test(10);
+
+DEALLOCATE on_empty_test;
+
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+
+-- ON EMPTY must NOT fire for a non-empty group whose rows are all NULL: such
+-- a group has processed rows, so the normal (NULL) result applies. This is
+-- exercised against a strict transition function (max/min/sum of int are
+-- handled differently, so test a strict one explicitly) and across the
+-- sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+
+-- strict transition function (max/min) over an all-NULL, non-empty group
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- NULL, not -1
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- NULL, not -1
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+RESET enable_sort; RESET enable_hashagg;
+
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- a strict ordered-set aggregate over an all-NULL group also processes rows,
+-- so ON EMPTY is not used (NULL); a truly empty input still uses it
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- NULL
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+
+-- the all-NULL behavior is the same for a window aggregate, which uses ON
+-- EMPTY only for a row whose frame contains no rows
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+
+-- ON EMPTY must be a constant: a correlated reference to an outer query's
+-- column is not constant and must be rejected (it is not caught by a
+-- current-level-only Var check)
+SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10;
+
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index 5ac3a486e16..4e66a83fb78 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -2190,3 +2190,58 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
+
+
+-- Test ON EMPTY clause with window functions
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+
+-- Frames with only NULL values (ON EMPTY value WILL NOT be returned)
+-- Row 4 has NULL, when frame contains only that row, should NOT return ON EMPTY value
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+
+-- Partition with only NULL values (ON EMPTY value WILL NOT be returned)
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+
+\d+ win_on_empty_vw
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
--
2.43.0
v1-0002-jit-Support-EEOP_AGG_INPUT_RECEIVED-in-the-LLVM-e.patch (application/octet-stream, 3.4K) download
From d5323f00de7191965a2ed70b70ed06fb91472586 Mon Sep 17 00:00:00 2001
From: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Date: Fri, 26 Jun 2026 12:54:24 +0530
Subject: [PATCH v1 2/2] jit: Support EEOP_AGG_INPUT_RECEIVED in the LLVM
expression compiler
Follow-on to the ON EMPTY aggregate/window support. That patch added
the EEOP_AGG_INPUT_RECEIVED expression step and implemented it in the
interpreter; this patch teaches the LLVM JIT to compile the same step
so that JIT-compiled aggregate transition expressions behave
identically to the interpreted ones.
The compiled step loads the aggregate's per-group state, skips
silently if that pointer is NULL (the hashed/spilled case), and
otherwise sets the group's inputReceived flag -- mirroring the
interpreter's EEOP_AGG_INPUT_RECEIVED case. Without this, building
with LLVM and JIT-compiling an ON EMPTY aggregate would fail on the
unhandled opcode.
Jeevan Chalke
---
src/backend/jit/llvm/llvmjit_expr.c | 63 +++++++++++++++++++++++++++++
1 file changed, 63 insertions(+)
diff --git a/src/backend/jit/llvm/llvmjit_expr.c b/src/backend/jit/llvm/llvmjit_expr.c
index 0e160b8502c..2684eb20a03 100644
--- a/src/backend/jit/llvm/llvmjit_expr.c
+++ b/src/backend/jit/llvm/llvmjit_expr.c
@@ -2594,6 +2594,69 @@ llvm_compile_expr(ExprState *state)
break;
}
+ case EEOP_AGG_INPUT_RECEIVED:
+ {
+ LLVMValueRef v_aggstatep;
+ LLVMValueRef v_allpergroupsp;
+ LLVMValueRef v_pergroup_allaggs;
+ LLVMValueRef v_setoff;
+ LLVMValueRef v_transno;
+ LLVMValueRef v_pergroupp;
+ LLVMBasicBlockRef b_mark;
+
+ /*
+ * Mark that the aggregate's per-group state has received
+ * an input row (used by the ON EMPTY clause). Matches
+ * the interpreter's EEOP_AGG_INPUT_RECEIVED: skip
+ * silently if the per-group pointer is NULL
+ * (hashed/spilled case).
+ */
+ v_aggstatep = LLVMBuildBitCast(b, v_parent,
+ l_ptr(StructAggState), "");
+
+ v_allpergroupsp = l_load_struct_gep(b,
+ StructAggState,
+ v_aggstatep,
+ FIELDNO_AGGSTATE_ALL_PERGROUPS,
+ "aggstate.all_pergroups");
+
+ v_setoff = l_int32_const(lc, op->d.agg_input_received.setoff);
+ v_transno = l_int32_const(lc, op->d.agg_input_received.transno);
+
+ v_pergroup_allaggs = l_load_gep1(b, l_ptr(StructAggStatePerGroupData),
+ v_allpergroupsp, v_setoff, "");
+
+ b_mark = l_bb_before_v(opblocks[opno + 1],
+ "op.%d.inputreceived", opno);
+
+ LLVMBuildCondBr(b,
+ LLVMBuildICmp(b, LLVMIntEQ,
+ LLVMBuildPtrToInt(b, v_pergroup_allaggs, TypeDatum, ""),
+ l_datum_const(0), ""),
+ opblocks[opno + 1],
+ b_mark);
+
+ /* block that performs the store when pergroup is non-NULL */
+ LLVMPositionBuilderAtEnd(b, b_mark);
+
+ v_pergroupp =
+ l_gep(b,
+ StructAggStatePerGroupData,
+ v_pergroup_allaggs,
+ &v_transno, 1, "");
+
+ LLVMBuildStore(b,
+ l_sbool_const(1),
+ l_struct_gep(b,
+ StructAggStatePerGroupData,
+ v_pergroupp,
+ FIELDNO_AGGSTATEPERGROUPDATA_INPUTRECEIVED,
+ "inputreceivedp"));
+
+ LLVMBuildBr(b, opblocks[opno + 1]);
+ break;
+ }
+
case EEOP_AGG_PLAIN_TRANS_INIT_STRICT_BYVAL:
case EEOP_AGG_PLAIN_TRANS_STRICT_BYVAL:
case EEOP_AGG_PLAIN_TRANS_BYVAL:
--
2.43.0
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-06-26 13:21 Isaac Morland <isaac.morland@gmail.com>
parent: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
0 siblings, 1 reply; 14+ messages in thread
From: Isaac Morland @ 2026-06-26 13:21 UTC (permalink / raw)
To: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; +Cc: pgsql-hackers
On Fri, 26 Jun 2026 at 05:12, Jeevan Chalke <jeevan.chalke@enterprisedb.com>
wrote:
> Hello Hackers,
>
> Here is a patch set adding an optional ON EMPTY clause to aggregate (and
> aggregate-as-window-function) calls. It supplies a value to return when
> the
> aggregate processes no input rows at all:
>
> agg_function(args, default_value ON EMPTY)
>
> For example:
>
> SELECT sum(i, -1 ON EMPTY)
> FROM generate_series(1,10) AS s(i) WHERE i > 100;
> sum
> -----
> -1
> (1 row)
>
> ON EMPTY is triggered only by an empty input set, not by NULL inputs that
> are
> ignored during aggregation. A FILTER that removes all rows makes the
> input
> set empty, so the default applies in that case too. Because a grouped
> query
> never produces empty groups, ON EMPTY takes effect for an ungrouped
> aggregate
> over zero rows, or for a group whose rows are all removed by FILTER. For
> an
> aggregate used as a window function, the default is returned for any row
> whose
> frame contains no rows. It also works with an ordered-set aggregate, with
> the
> default written before WITHIN GROUP:
>
Is there any chance of storing a default default_value with the aggregate?
I ask because for most aggregate functions there is a specific value for
each function which is almost always what will be wanted, e.g., 0 for sum,
-Infinity for max, +Infinity for min, 1 for multiplication (if the other
proposal for a multiplication aggregate is accepted), and so on, generally
characterizable as the identity element for the function in question. Only
in rare cases would one actually want to override the identity and use some
other specified value.
I was going to suggest there would need to be an additional clause for
CREATE AGGREGATE, but I see there is already an INITCOND parameter which in
principle should already be doing the job (except that as I understand it
the aggregate isn't invoked at all for empty input?).
Also I'm not entirely happy with the name "default_value". It's not really
a default, just the value of the aggregate at empty input. Unfortunately, I
don't have a better suggestion.
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-06-28 12:56 Jeevan Chalke <jeevan.chalke@enterprisedb.com>
parent: Isaac Morland <isaac.morland@gmail.com>
0 siblings, 1 reply; 14+ messages in thread
From: Jeevan Chalke @ 2026-06-28 12:56 UTC (permalink / raw)
To: Isaac Morland <isaac.morland@gmail.com>; +Cc: pgsql-hackers
Hello Isaac,
Good points on both counts.
Regarding INITCOND, you are correct that it only sets the initial state.
I tried exploiting it in my very first attempt too. However, if the
aggregate isn't invoked at all (zero input rows), INITCOND is never
used to determine the final result, which is why we need this mechanism
to return something at finalization when the input set was empty.
The majority of the code changes here are to determine whether we've
received any input or not.
I'm open to renaming 'default_value' if a better term comes up.
'Value_at_empty_input' is certainly more precise than 'default',
but it's long. I'll keep an eye out for other suggestions; I'm not
attached to the current name and will be happy to rename it once we
settle on one.
Thanks for reviewing.
On Fri, Jun 26, 2026 at 6:51 PM Isaac Morland <isaac.morland@gmail.com>
wrote:
> On Fri, 26 Jun 2026 at 05:12, Jeevan Chalke <
> jeevan.chalke@enterprisedb.com> wrote:
>
>> Hello Hackers,
>>
>> Here is a patch set adding an optional ON EMPTY clause to aggregate (and
>> aggregate-as-window-function) calls. It supplies a value to return when
>> the
>> aggregate processes no input rows at all:
>>
>> agg_function(args, default_value ON EMPTY)
>>
>> For example:
>>
>> SELECT sum(i, -1 ON EMPTY)
>> FROM generate_series(1,10) AS s(i) WHERE i > 100;
>> sum
>> -----
>> -1
>> (1 row)
>>
>> ON EMPTY is triggered only by an empty input set, not by NULL inputs
>> that are
>> ignored during aggregation. A FILTER that removes all rows makes the
>> input
>> set empty, so the default applies in that case too. Because a grouped
>> query
>> never produces empty groups, ON EMPTY takes effect for an ungrouped
>> aggregate
>> over zero rows, or for a group whose rows are all removed by FILTER.
>> For an
>> aggregate used as a window function, the default is returned for any row
>> whose
>> frame contains no rows. It also works with an ordered-set aggregate,
>> with the
>> default written before WITHIN GROUP:
>>
>
> Is there any chance of storing a default default_value with the aggregate?
> I ask because for most aggregate functions there is a specific value for
> each function which is almost always what will be wanted, e.g., 0 for sum,
> -Infinity for max, +Infinity for min, 1 for multiplication (if the other
> proposal for a multiplication aggregate is accepted), and so on, generally
> characterizable as the identity element for the function in question. Only
> in rare cases would one actually want to override the identity and use some
> other specified value.
>
> I was going to suggest there would need to be an additional clause for
> CREATE AGGREGATE, but I see there is already an INITCOND parameter which in
> principle should already be doing the job (except that as I understand it
> the aggregate isn't invoked at all for empty input?).
>
> Also I'm not entirely happy with the name "default_value". It's not really
> a default, just the value of the aggregate at empty input. Unfortunately, I
> don't have a better suggestion.
>
--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*
enterprisedb.com <https://www.enterprisedb.com;
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-12 13:18 Jeevan Chalke <jeevan.chalke@enterprisedb.com>
parent: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
0 siblings, 2 replies; 14+ messages in thread
From: Jeevan Chalke @ 2026-09-12 13:18 UTC (permalink / raw)
To: pgsql-hackers; +Cc: Vik Fearing <vik@postgresfriends.org>; Tom Lane <tgl@sss.pgh.pa.us>; Isaac Morland <isaac.morland@gmail.com>
Hackers,
Following up on this thread (and the related discussion on the PRODUCT()
thread
https://www.postgresql.org/message-id/flat/CAM2%2B6%3DWG8gpOti%2B1-N_ra0mNcNrdhMjSJcDvcA7wzjLD-qKH3g...
):
I've reworked the ON EMPTY patch and would like feedback on the new
design before going further.
Thanks to Tom for pointing out the strict/non-strict distinction, and to Vik
for quoting the SQL committee's actual definition on the PRODUCT() thread:
PRODUCT(SQ VE, 1 ON EMPTY) => COALESCE(PRODUCT(SQ VE), 1)
i.e. the standard defines ON EMPTY, for the aggregates it actually
standardizes (SUM/PRODUCT), as nothing more than COALESCE over the whole
aggregate result. That prompted me to implement the general (PG extension)
version the same way.
What changed
---
ON EMPTY is now implemented as exactly:
agg(args, default ON EMPTY) == COALESCE(agg(args), default)
for both plain and window aggregates: compute the aggregate's ordinary
result exactly as without ON EMPTY, and substitute the default only if that
result is NULL. No new expression-evaluation step, no per-row bookkeeping,
and no restriction on partial/parallel aggregation.
The earlier design instead tracked, per group, whether any row was actually
fed to the transition function (to distinguish true emptiness from input
that merely computes to NULL). I dropped it: testing showed some built-in
aggregates use a differently-strict transition function for plain vs.
windowed use (e.g. sum(int4): int4_sum, non-strict, vs. int4_avg_accum,
strict), so the same clause over the same all-NULL data fired for a
windowed sum() but not a plain one. That's an implementation detail
leaking into user-visible behavior, not something worth preserving.
As a side benefit, the earlier restriction disabling partial/parallel
aggregation for ON EMPTY aggregates is also gone -- finalization always
happens centrally, so the COALESCE check works regardless of how the
transition state was combined.
The tradeoff, stated plainly
---
Because it's exactly COALESCE, ON EMPTY can't distinguish "zero rows" from
"rows were processed, but the result is legitimately NULL", for any
aggregate. For example, `stddev(x, -1 ON EMPTY)` over a single row returns
-1, even though that row was genuinely processed (stddev_samp of one value
is undefined and NULL by definition). Same story for percentile_cont over a
non-empty, all-NULL input.
I'd rather have a simple, uniform rule with a stated limitation than a
"smarter" rule that disagrees with itself depending on plan shape. Open to
recovering the stricter distinction for a subset of aggregates if there's
appetite for it, but I don't think it should be the default.
Patch and testing
---
Now a single patch (the earlier JIT-support patch is gone, since ON EMPTY no
longer needs a new expression step for the JIT compiler to support). Full
regression suite passes, including under a forced-JIT build.
Thanks,
On Sun, Jun 28, 2026 at 6:26 PM Jeevan Chalke <
jeevan.chalke@enterprisedb.com> wrote:
> Hello Isaac,
>
> Good points on both counts.
>
> Regarding INITCOND, you are correct that it only sets the initial state.
> I tried exploiting it in my very first attempt too. However, if the
> aggregate isn't invoked at all (zero input rows), INITCOND is never
> used to determine the final result, which is why we need this mechanism
> to return something at finalization when the input set was empty.
> The majority of the code changes here are to determine whether we've
> received any input or not.
>
> I'm open to renaming 'default_value' if a better term comes up.
> 'Value_at_empty_input' is certainly more precise than 'default',
> but it's long. I'll keep an eye out for other suggestions; I'm not
> attached to the current name and will be happy to rename it once we
> settle on one.
>
> Thanks for reviewing.
>
> On Fri, Jun 26, 2026 at 6:51 PM Isaac Morland <isaac.morland@gmail.com>
> wrote:
>
>> On Fri, 26 Jun 2026 at 05:12, Jeevan Chalke <
>> jeevan.chalke@enterprisedb.com> wrote:
>>
>>> Hello Hackers,
>>>
>>> Here is a patch set adding an optional ON EMPTY clause to aggregate (and
>>> aggregate-as-window-function) calls. It supplies a value to return when
>>> the
>>> aggregate processes no input rows at all:
>>>
>>> agg_function(args, default_value ON EMPTY)
>>>
>>> For example:
>>>
>>> SELECT sum(i, -1 ON EMPTY)
>>> FROM generate_series(1,10) AS s(i) WHERE i > 100;
>>> sum
>>> -----
>>> -1
>>> (1 row)
>>>
>>> ON EMPTY is triggered only by an empty input set, not by NULL inputs
>>> that are
>>> ignored during aggregation. A FILTER that removes all rows makes the
>>> input
>>> set empty, so the default applies in that case too. Because a grouped
>>> query
>>> never produces empty groups, ON EMPTY takes effect for an ungrouped
>>> aggregate
>>> over zero rows, or for a group whose rows are all removed by FILTER.
>>> For an
>>> aggregate used as a window function, the default is returned for any row
>>> whose
>>> frame contains no rows. It also works with an ordered-set aggregate,
>>> with the
>>> default written before WITHIN GROUP:
>>>
>>
>> Is there any chance of storing a default default_value with the
>> aggregate? I ask because for most aggregate functions there is a specific
>> value for each function which is almost always what will be wanted, e.g., 0
>> for sum, -Infinity for max, +Infinity for min, 1 for multiplication (if the
>> other proposal for a multiplication aggregate is accepted), and so on,
>> generally characterizable as the identity element for the function in
>> question. Only in rare cases would one actually want to override the
>> identity and use some other specified value.
>>
>> I was going to suggest there would need to be an additional clause for
>> CREATE AGGREGATE, but I see there is already an INITCOND parameter which in
>> principle should already be doing the job (except that as I understand it
>> the aggregate isn't invoked at all for empty input?).
>>
>> Also I'm not entirely happy with the name "default_value". It's not
>> really a default, just the value of the aggregate at empty input.
>> Unfortunately, I don't have a better suggestion.
>>
>
>
> --
> *Jeevan Chalke*
> *Senior Principal Engineer, Engineering Manager*
> *Product Development*
>
> enterprisedb.com <https://www.enterprisedb.com;
>
--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*
enterprisedb.com <https://www.enterprisedb.com;
Attachments:
v2-0001-Add-support-for-ON-EMPTY-clause-in-aggregate-and-.patch (application/octet-stream, 69.0K) download
From 9c76737d860001a96d9938e276b8229e9cba5e64 Mon Sep 17 00:00:00 2001
From: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Date: Sat, 12 Sep 2026 17:20:33 +0530
Subject: [PATCH v2] Add support for ON EMPTY clause in aggregate and window
functions
Add an ON EMPTY clause for aggregate (and aggregate-as-window-
function) calls, returning a default when the aggregate's normal
result would otherwise be NULL:
agg(args, default ON EMPTY) == COALESCE(agg(args), default)
for both plain and window aggregates. This matches the SQL
committee's own definition of ON EMPTY for SUM/PRODUCT (per Vik
Fearing on -hackers), generalized here to arbitrary aggregates.
Implemented as a single NULL check at finalization time, after
computing the aggregate normally. No new expression step, no
per-row state, and no restriction on partial/parallel aggregation.
Since aggregates can share transition state across calls with the
same transfn/args/filter, find_compatible_agg() and ExecInitAgg()
must treat aggonempty as part of what makes two calls distinct,
and build each call's ON EMPTY state independently of that sharing.
The default expression must be a constant-like expression coercible
to the aggregate's result type. It may not reference columns (at
any query level) or contain aggregates, window functions,
subqueries, or volatile functions. ON EMPTY cannot be combined with
DISTINCT, and is rejected for non-aggregate window functions; it may
be used with an ordered-set (WITHIN GROUP) aggregate, written before
the WITHIN GROUP clause.
Patch also includes documentation and regression tests for
aggregates and window functions, covering empty tables, filtered
results, type coercion, all-NULL inputs, GROUP BY and grouping sets,
ordered-set aggregates, forced-parallel plans, multiple ON EMPTY
calls sharing transition state, and view deparsing.
This commit adds fields to Aggref and WindowFunc (and FuncCall).
These node types are serialized into pg_rewrite (views/rules) and
other stored expression trees, which requires a CATALOG_VERSION_NO
bump. That is omitted here to avoid conflicts with concurrent
commits; the committer should bump it at commit time.
Proposed-by: Peter Eisentraut
Jeevan Chalke
---
doc/src/sgml/syntax.sgml | 50 +++
src/backend/executor/nodeAgg.c | 22 +
src/backend/executor/nodeWindowAgg.c | 20 +
src/backend/nodes/makefuncs.c | 1 +
src/backend/nodes/nodeFuncs.c | 8 +
src/backend/optimizer/prep/prepagg.c | 3 +-
src/backend/optimizer/util/clauses.c | 6 +
src/backend/parser/gram.y | 16 +
src/backend/parser/parse_agg.c | 134 +++++-
src/backend/parser/parse_expr.c | 11 +-
src/backend/parser/parse_func.c | 37 +-
src/backend/utils/adt/ruleutils.c | 22 +
src/include/executor/nodeAgg.h | 3 +
src/include/nodes/parsenodes.h | 1 +
src/include/nodes/primnodes.h | 5 +
src/include/parser/parse_agg.h | 4 +-
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/aggregates.out | 521 +++++++++++++++++++++++
src/test/regress/expected/window.out | 131 ++++++
src/test/regress/sql/aggregates.sql | 222 ++++++++++
src/test/regress/sql/window.sql | 70 +++
21 files changed, 1279 insertions(+), 9 deletions(-)
diff --git a/doc/src/sgml/syntax.sgml b/doc/src/sgml/syntax.sgml
index 67482996861..9584f1f052f 100644
--- a/doc/src/sgml/syntax.sgml
+++ b/doc/src/sgml/syntax.sgml
@@ -1555,6 +1555,10 @@ sqrt(2)
<primary>FILTER</primary>
</indexterm>
+ <indexterm zone="syntax-aggregates">
+ <primary>ON EMPTY</primary>
+ </indexterm>
+
<para>
An <firstterm>aggregate expression</firstterm> represents the
application of an aggregate function across the rows selected by a
@@ -1564,6 +1568,7 @@ sqrt(2)
<synopsis>
<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
+<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] , <replaceable>default_expression</replaceable> ON EMPTY [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> ( * ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
@@ -1744,6 +1749,38 @@ FROM generate_series(1,10) AS s(i);
</programlisting>
</para>
+ <para>
+ If <literal>ON EMPTY</literal> is specified, then
+ <replaceable>default_expression</replaceable> supplies the value of the
+ aggregate whenever its normal result would otherwise be null; that is,
+ <literal>agg(<replaceable>args</replaceable>,
+ <replaceable>default_expression</replaceable> ON EMPTY)</literal> is
+ equivalent to <literal>COALESCE(agg(<replaceable>args</replaceable>),
+ <replaceable>default_expression</replaceable>)</literal>, including for
+ an aggregate used as a window function. In particular, this fires not
+ only for a truly empty input (no rows at all, or none passing a
+ <replaceable>filter_clause</replaceable>), but for any other reason the
+ aggregate's ordinary result happens to be null, such as a group whose
+ rows are all null, or a statistical aggregate like
+ <function>stddev</function> or <function>corr</function> returning null
+ for insufficient or degenerate data. <literal>ON EMPTY</literal> cannot
+ distinguish these cases from true emptiness. For example:
+<programlisting>
+SELECT sum(i) AS plain, sum(i, -1 ON EMPTY) AS defaulted
+FROM generate_series(1,10) AS s(i) WHERE i > 100;
+ plain | defaulted
+-------+-----------
+ | -1
+(1 row)
+</programlisting>
+ <replaceable>default_expression</replaceable> must be a constant-like
+ expression of a type coercible to the aggregate's result type: it may not
+ refer to columns or contain aggregates, window functions, subqueries, or
+ volatile functions. <literal>ON EMPTY</literal> cannot be combined with
+ <literal>DISTINCT</literal>. It may be used with an ordered-set
+ aggregate, written before the <literal>WITHIN GROUP</literal> clause.
+ </para>
+
<para>
The predefined aggregate functions are described in <xref
linkend="functions-aggregate"/>. Other aggregate functions can be added
@@ -1843,6 +1880,19 @@ EXCLUDE NO OTHERS
described in <xref linkend="functions-window"/>.
</para>
+ <para>
+ When an aggregate function is used as a window function, an
+ <literal>ON EMPTY</literal> clause may be given after its arguments
+ (using the same syntax as for a plain aggregate call, described in
+ <xref linkend="syntax-aggregates"/>), with the same
+ <literal>COALESCE</literal>-equivalent behavior applied per output row:
+ the <replaceable>default_expression</replaceable> is returned for any row
+ whose windowed result would otherwise be null, which includes every row
+ whose window frame contains no rows (including a frame that becomes
+ empty as the frame moves). <literal>ON EMPTY</literal> is not accepted
+ for non-aggregate window functions.
+ </para>
+
<para>
<replaceable>window_name</replaceable> is a reference to a named window
specification defined in the query's <literal>WINDOW</literal> clause.
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 29037cf3122..28c22104799 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -1133,6 +1133,16 @@ finalize_aggregate(AggState *aggstate,
*resultIsNull = pergroupstate->transValueIsNull;
}
+ /*
+ * If an ON EMPTY default is specified and the normal result came out
+ * NULL, substitute the default -- i.e. this is exactly
+ * COALESCE(normal_result, default_expression).
+ */
+ if (peragg->aggonemptystate != NULL && *resultIsNull)
+ *resultVal = ExecEvalExpr(peragg->aggonemptystate,
+ aggstate->ss.ps.ps_ExprContext,
+ resultIsNull);
+
MemoryContextSwitchTo(oldContext);
}
@@ -4039,6 +4049,18 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
else
pertrans->aggshared = true;
ReleaseSysCache(aggTuple);
+
+ /*
+ * Build expression state for the ON EMPTY default expression. This
+ * is per-aggregate (peragg), not per-transition-state, so it must be
+ * done for every aggref even when its transition state is shared
+ * with another aggregate that already built its pertrans above.
+ */
+ if (aggref->aggonempty)
+ peragg->aggonemptystate = ExecInitExpr(aggref->aggonempty,
+ (PlanState *) aggstate);
+ else
+ peragg->aggonemptystate = NULL;
}
/*
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index b86dcbba055..567c542ed11 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -171,6 +171,9 @@ typedef struct WindowStatePerAggData
/* Data local to eval_windowaggregates() */
bool restart; /* need to restart this agg in this cycle? */
+
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} WindowStatePerAggData;
static void initialize_windowaggregate(WindowAggState *winstate,
@@ -691,6 +694,16 @@ finalize_windowaggregate(WindowAggState *winstate,
*isnull = peraggstate->transValueIsNull;
}
+ /*
+ * If an ON EMPTY default is specified and the normal result came out
+ * NULL, substitute the default -- i.e. this is exactly
+ * COALESCE(normal_result, default_expression).
+ */
+ if (peraggstate->aggonemptystate != NULL && *isnull)
+ *result = ExecEvalExpr(peraggstate->aggonemptystate,
+ winstate->ss.ps.ps_ExprContext,
+ isnull);
+
MemoryContextSwitchTo(oldContext);
}
@@ -3164,6 +3177,13 @@ initialize_peragg(WindowAggState *winstate, WindowFunc *wfunc,
&peraggstate->transtypeLen,
&peraggstate->transtypeByVal);
+ /* Build expression state for ON EMPTY default expression */
+ if (wfunc->aggonempty)
+ peraggstate->aggonemptystate = ExecInitExpr(wfunc->aggonempty,
+ (PlanState *) winstate);
+ else
+ peraggstate->aggonemptystate = NULL;
+
/*
* initval is potentially null, so don't try to access it as a struct
* field. Must do it the hard way with SysCacheGetAttr.
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index cdc02b274ff..a5e26c28a51 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -681,6 +681,7 @@ makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
n->args = args;
n->agg_order = NIL;
n->agg_filter = NULL;
+ n->agg_on_empty = NULL;
n->over = NULL;
n->agg_within_group = false;
n->agg_star = false;
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 9eb905fd025..7e4df76bbdb 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -2158,6 +2158,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
}
break;
case T_GroupingFunc:
@@ -2177,6 +2179,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
if (WALK(expr->runCondition))
return true;
}
@@ -3061,6 +3065,7 @@ expression_tree_mutator_impl(Node *node,
MUTATE(newnode->aggorder, aggref->aggorder, List *);
MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
MUTATE(newnode->aggfilter, aggref->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, aggref->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -3095,6 +3100,7 @@ expression_tree_mutator_impl(Node *node,
FLATCOPY(newnode, wfunc, WindowFunc);
MUTATE(newnode->args, wfunc->args, List *);
MUTATE(newnode->aggfilter, wfunc->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, wfunc->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -4464,6 +4470,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(fcall->agg_filter))
return true;
+ if (WALK(fcall->agg_on_empty))
+ return true;
if (WALK(fcall->over))
return true;
/* function name is deemed uninteresting */
diff --git a/src/backend/optimizer/prep/prepagg.c b/src/backend/optimizer/prep/prepagg.c
index 3737cc15ba1..17d3a8dd474 100644
--- a/src/backend/optimizer/prep/prepagg.c
+++ b/src/backend/optimizer/prep/prepagg.c
@@ -423,7 +423,8 @@ find_compatible_agg(PlannerInfo *root, Aggref *newagg,
if (newagg->aggfnoid == existingRef->aggfnoid &&
newagg->aggtype == existingRef->aggtype &&
newagg->aggcollid == existingRef->aggcollid &&
- equal(newagg->aggdirectargs, existingRef->aggdirectargs))
+ equal(newagg->aggdirectargs, existingRef->aggdirectargs) &&
+ equal(newagg->aggonempty, existingRef->aggonempty))
{
list_free(*same_input_transnos);
*same_input_transnos = NIL;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 55cebe4a74b..3a217240c7d 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -2894,6 +2894,7 @@ eval_const_expressions_mutator(Node *node,
Oid funcid = expr->winfnoid;
List *args;
Expr *aggfilter;
+ Expr *aggonempty;
HeapTuple func_tuple;
WindowFunc *newexpr;
@@ -2923,6 +2924,10 @@ eval_const_expressions_mutator(Node *node,
aggfilter = (Expr *)
eval_const_expressions_mutator((Node *) expr->aggfilter,
context);
+ /* ... and the ON EMPTY expression */
+ aggonempty = (Expr *)
+ eval_const_expressions_mutator((Node *) expr->aggonempty,
+ context);
/* And build the replacement WindowFunc node */
newexpr = makeNode(WindowFunc);
@@ -2932,6 +2937,7 @@ eval_const_expressions_mutator(Node *node,
newexpr->inputcollid = expr->inputcollid;
newexpr->args = args;
newexpr->aggfilter = aggfilter;
+ newexpr->aggonempty = aggonempty;
newexpr->runCondition = expr->runCondition;
newexpr->winref = expr->winref;
newexpr->winstar = expr->winstar;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 1015d303fbf..f973341df88 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -464,6 +464,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <list> group_by_list
%type <node> group_by_item empty_grouping_set rollup_clause cube_clause
%type <node> grouping_sets_clause
+%type <node> on_empty
%type <list> opt_fdw_options fdw_options
%type <defelt> fdw_option
@@ -16149,6 +16150,16 @@ func_application: func_name '(' ')'
n->agg_order = $7;
$$ = (Node *) n;
}
+ | func_name '(' func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $3,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $5;
+ n->agg_order = $6;
+ $$ = (Node *) n;
+ }
| func_name '(' ALL func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16194,6 +16205,11 @@ func_application: func_name '(' ')'
;
+on_empty: a_expr ON EMPTY_P
+ { $$ = $1; }
+ ;
+
+
/*
* func_expr and its cousin func_expr_windowless are split out from c_expr just
* so that we have classifications for "everything that is a function call or
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index fac401e85d5..63d221f8219 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -21,6 +21,7 @@
#include "common/int.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
+#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
@@ -82,6 +83,9 @@ static Var *buildGroupedVar(int attnum, Index ressortgroupref,
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
static List *expand_groupingset_node(GroupingSet *gs);
static Node *make_agg_arg(Oid argtype, Oid argcollation);
+static Node *check_agg_on_empty(ParseState *pstate, Oid aggtype,
+ Expr *agg_on_empty, int location);
+static bool agg_on_empty_contains_var_walker(Node *node, void *context);
/*
@@ -111,7 +115,8 @@ static Node *make_agg_arg(Oid argtype, Oid argcollation);
*/
void
transformAggregateCall(ParseState *pstate, Aggref *agg,
- List *args, List *aggorder, bool agg_distinct)
+ List *args, List *aggorder, bool agg_distinct,
+ Expr *agg_on_empty)
{
List *argtypes = NIL;
List *tlist = NIL;
@@ -231,6 +236,8 @@ transformAggregateCall(ParseState *pstate, Aggref *agg,
agg->args = tlist;
agg->aggorder = torder;
agg->aggdistinct = tdistinct;
+ agg->aggonempty = (Expr *) check_agg_on_empty(pstate, agg->aggtype,
+ agg_on_empty, agg->location);
/*
* Now build the aggargtypes list with the type OIDs of the direct and
@@ -499,6 +506,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
else
err = _("grouping operations are not allowed in DEFAULT expressions");
+ break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+
+ if (isAgg)
+ err = _("aggregate functions are not allowed in ON EMPTY expressions");
+ else
+ err = _("grouping operations are not allowed in ON EMPTY expressions");
+
break;
case EXPR_KIND_INDEX_EXPRESSION:
if (isAgg)
@@ -884,7 +899,7 @@ check_agg_arguments_walker(Node *node,
*/
void
transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef)
+ WindowDef *windef, Expr *agg_on_empty)
{
const char *err;
bool errkind;
@@ -995,6 +1010,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("window functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("window functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("window functions are not allowed in index expressions");
break;
@@ -1129,6 +1147,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
}
pstate->p_hasWindowFuncs = true;
+ wfunc->aggonempty = (Expr *) check_agg_on_empty(pstate, wfunc->wintype,
+ agg_on_empty,
+ wfunc->location);
}
/*
@@ -2413,3 +2434,112 @@ make_agg_arg(Oid argtype, Oid argcollation)
argp->location = -1;
return (Node *) argp;
}
+
+/*
+ * check_agg_on_empty -
+ * Checks the aggregate's ON EMPTY expression for correctness.
+ */
+static Node *
+check_agg_on_empty(ParseState *pstate, Oid aggtype, Expr *agg_on_empty,
+ int location)
+{
+ Oid defexprtype;
+
+ if (!agg_on_empty)
+ return NULL;
+
+ /*
+ * default expression must be a constant - it cannot contain column
+ * references (Var nodes), aggregates, or window functions.
+ *
+ * Note we cannot use contain_var_clause() here: it only detects Vars of
+ * the current query level, so a correlated reference to an outer query's
+ * column (varlevelsup > 0) would slip through and make the "constant"
+ * default vary per outer row. Reject Vars of any level.
+ */
+ if (agg_on_empty_contains_var_walker((Node *) agg_on_empty, NULL))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must be a constant value"),
+ parser_errposition(pstate, location)));
+
+ if (contain_agg_clause((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain an aggregate function"),
+ parser_errposition(pstate, location)));
+
+ if (contain_windowfuncs((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a window function"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * Sub-selects are not constant and, more importantly, the ON EMPTY
+ * expression is only run through ExecInitExpr() at execution time, never
+ * the sub-plan setup that a normal target expression receives, so a
+ * sub-select here would fail (or crash) at execution. Reject it.
+ */
+ if (checkExprHasSubLink((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a subquery"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * The default is evaluated only once, for the empty-input case, so a
+ * volatile expression would not behave like a per-row value. Restrict it
+ * to a stable/immutable, constant-like expression.
+ */
+ if (contain_volatile_functions((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a volatile function"),
+ parser_errposition(pstate, location)));
+
+ defexprtype = exprType((Node *) agg_on_empty);
+
+ /* default expression must be coercible to the aggregate's result type. */
+ agg_on_empty = (Expr *) coerce_to_target_type(pstate,
+ (Node *) agg_on_empty,
+ defexprtype,
+ aggtype,
+ -1,
+ COERCION_ASSIGNMENT,
+ COERCE_IMPLICIT_CAST,
+ -1);
+
+ if (agg_on_empty == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("ON EMPTY expression type %s cannot be coerced to aggregate result type %s",
+ format_type_be(defexprtype),
+ format_type_be(aggtype)),
+ parser_errposition(pstate, location)));
+
+ return (Node *) agg_on_empty;
+}
+
+/*
+ * agg_on_empty_contains_var_walker -
+ * Returns true if the node tree contains any Var (a column reference) or
+ * CurrentOfExpr, regardless of query level.
+ *
+ * Unlike contain_var_clause(), this also reports Vars belonging to outer
+ * query levels (varlevelsup > 0), which is what we need to ensure an ON EMPTY
+ * default really is constant. Sub-selects are rejected separately, so there
+ * is no need to descend into them here. This runs during parse analysis, so
+ * PlaceHolderVars (which the planner introduces) cannot appear; a Var inside
+ * one would be caught by the recursion anyway.
+ */
+static bool
+agg_on_empty_contains_var_walker(Node *node, void *context)
+{
+ if (node == NULL)
+ return false;
+ if (IsA(node, Var) || IsA(node, CurrentOfExpr))
+ return true;
+ return expression_tree_walker(node, agg_on_empty_contains_var_walker,
+ context);
+}
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index e4acc67851b..c06b55d857a 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -566,6 +566,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_CHECK_CONSTRAINT:
case EXPR_KIND_DOMAIN_CHECK:
case EXPR_KIND_FUNCTION_DEFAULT:
+ case EXPR_KIND_AGG_ON_EMPTY:
case EXPR_KIND_INDEX_EXPRESSION:
case EXPR_KIND_INDEX_PREDICATE:
case EXPR_KIND_STATS_EXPRESSION:
@@ -1841,6 +1842,9 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("cannot use subquery in DEFAULT expression");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("cannot use subquery in ON EMPTY expression");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("cannot use subquery in index expression");
break;
@@ -3212,6 +3216,8 @@ ParseExprKindName(ParseExprKind exprKind)
case EXPR_KIND_COLUMN_DEFAULT:
case EXPR_KIND_FUNCTION_DEFAULT:
return "DEFAULT";
+ case EXPR_KIND_AGG_ON_EMPTY:
+ return "ON EMPTY";
case EXPR_KIND_INDEX_EXPRESSION:
return "index expression";
case EXPR_KIND_INDEX_PREDICATE:
@@ -3977,7 +3983,7 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
parser_errposition(pstate, agg_ctor->location));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, agg_ctor->over);
+ transformWindowFuncCall(pstate, wfunc, agg_ctor->over, NULL);
node = (Node *) wfunc;
}
@@ -4004,7 +4010,8 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
aggref->aggtransno = -1;
aggref->location = agg_ctor->location;
- transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order, false);
+ transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order,
+ false, NULL);
node = (Node *) aggref;
}
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 52c4d072f0a..1392e9a4c5d 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -95,6 +95,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
Expr *agg_filter = NULL;
+ Expr *agg_on_empty = NULL;
WindowDef *over = (fn ? fn->over : NULL);
bool agg_within_group = (fn ? fn->agg_within_group : false);
bool agg_star = (fn ? fn->agg_star : false);
@@ -130,6 +131,15 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
EXPR_KIND_FILTER,
"FILTER");
+ /*
+ * If there's an aggregate ON EMPTY default value given, transform it
+ * here. It is parsed in its own expression kind so that disallowed
+ * constructs are reported as occurring "in ON EMPTY expressions".
+ */
+ if (fn && fn->agg_on_empty != NULL)
+ agg_on_empty = (Expr *) transformExpr(pstate, fn->agg_on_empty,
+ EXPR_KIND_AGG_ON_EMPTY);
+
/*
* Most of the rest of the parser just assumes that functions do not have
* more than FUNC_MAX_ARGS parameters. We have to test here to protect
@@ -226,6 +236,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
*/
could_be_projection = (nargs == 1 && !proc_call &&
agg_order == NIL && agg_filter == NULL &&
+ agg_on_empty == NULL &&
!agg_star && !agg_distinct && over == NULL &&
!func_variadic && argnames == NIL &&
list_length(funcname) == 1 &&
@@ -339,6 +350,12 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("ORDER BY specified, but %s is not an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+ if (agg_on_empty != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("ON EMPTY specified, but %s is not an aggregate function",
+ NameListToString(funcname)),
+ parser_errposition(pstate, location)));
if (agg_filter)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
@@ -876,7 +893,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional aggregate-specific processing */
- transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
+ transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct,
+ agg_on_empty);
retval = (Node *) aggref;
}
@@ -951,6 +969,18 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("FILTER is not implemented for non-aggregate window functions"),
parser_errposition(pstate, location)));
+ /*
+ * ON EMPTY only has meaning for aggregates: it supplies the value to
+ * return when the aggregate processes no rows. A true window
+ * function does not aggregate input rows, so it would be silently
+ * ignored; reject it instead.
+ */
+ if (!wfunc->winagg && agg_on_empty)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("ON EMPTY is not implemented for non-aggregate window functions"),
+ parser_errposition(pstate, location)));
+
/*
* Window functions can't either take or return sets
*/
@@ -969,7 +999,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, over);
+ transformWindowFuncCall(pstate, wfunc, over, agg_on_empty);
retval = (Node *) wfunc;
}
@@ -2806,6 +2836,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("set-returning functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("set-returning functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("set-returning functions are not allowed in index expressions");
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index f42263bf9c9..0446d34244d 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -10994,6 +10994,14 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
*/
Assert(!aggref->aggvariadic);
get_rule_expr((Node *) aggref->aggdirectargs, context, true);
+
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
Assert(aggref->aggorder != NIL);
appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
get_rule_orderby(aggref->aggorder, aggref->args, false, context);
@@ -11039,6 +11047,13 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
}
}
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (aggref->aggorder != NIL)
{
appendStringInfoString(buf, " ORDER BY ");
@@ -11139,6 +11154,13 @@ get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
get_rule_expr((Node *) wfunc->args, context, true);
}
+ if (wfunc->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) wfunc->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (options)
appendStringInfoString(buf, options);
diff --git a/src/include/executor/nodeAgg.h b/src/include/executor/nodeAgg.h
index 1e1be9666ae..de3b751e30d 100644
--- a/src/include/executor/nodeAgg.h
+++ b/src/include/executor/nodeAgg.h
@@ -229,6 +229,9 @@ typedef struct AggStatePerAggData
* aggregates because the final function is read-write.
*/
bool shareable;
+
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} AggStatePerAggData;
/*
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 910eef936f1..919ff8622c3 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -461,6 +461,7 @@ typedef struct FuncCall
bool agg_within_group; /* ORDER BY appeared in WITHIN GROUP */
bool agg_star; /* argument was really '*' */
bool agg_distinct; /* arguments were labeled DISTINCT */
+ Node *agg_on_empty; /* user given value to use ON EMPTY set */
bool func_variadic; /* last argument was labeled VARIADIC */
CoercionForm funcformat; /* how to display this node */
ParseLoc location; /* token location, or -1 if unknown */
diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h
index 09b0c29408c..6b11f236295 100644
--- a/src/include/nodes/primnodes.h
+++ b/src/include/nodes/primnodes.h
@@ -497,6 +497,9 @@ typedef struct Aggref
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
+
/* true if argument list was really '*' */
bool aggstar pg_node_attr(query_jumble_ignore);
@@ -602,6 +605,8 @@ typedef struct WindowFunc
List *args;
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
/* List of WindowFuncRunConditions to help short-circuit execution */
List *runCondition pg_node_attr(query_jumble_ignore);
/* index of associated WindowClause */
diff --git a/src/include/parser/parse_agg.h b/src/include/parser/parse_agg.h
index 8a5653798db..f93e956b83e 100644
--- a/src/include/parser/parse_agg.h
+++ b/src/include/parser/parse_agg.h
@@ -17,12 +17,12 @@
extern void transformAggregateCall(ParseState *pstate, Aggref *agg,
List *args, List *aggorder,
- bool agg_distinct);
+ bool agg_distinct, Expr *agg_on_empty);
extern Node *transformGroupingFunc(ParseState *pstate, GroupingFunc *p);
extern void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef);
+ WindowDef *windef, Expr *agg_on_empty);
extern void parseCheckAggregates(ParseState *pstate, Query *qry);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index 3eaeb7a90e1..2567c0e6ede 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -70,6 +70,7 @@ typedef enum ParseExprKind
EXPR_KIND_DOMAIN_CHECK, /* CHECK constraint for a domain */
EXPR_KIND_COLUMN_DEFAULT, /* default value for a table column */
EXPR_KIND_FUNCTION_DEFAULT, /* default parameter value for function */
+ EXPR_KIND_AGG_ON_EMPTY, /* aggregate/window ON EMPTY default value */
EXPR_KIND_INDEX_EXPRESSION, /* index expression */
EXPR_KIND_INDEX_PREDICATE, /* index predicate */
EXPR_KIND_STATS_EXPRESSION, /* extended statistics expression */
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 7d07619956f..5414840ddc4 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -3958,3 +3958,524 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+-- Test ON EMPTY clause for aggregates
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+ sum
+-----
+ -1
+(1 row)
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ -1
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+ 0
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ max
+-----
+ 999
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ min
+------
+ -999
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ count
+-------
+ 0
+(1 row)
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum
+-----
+ 30
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ max
+-----
+ 20
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ min
+-----
+ 10
+(1 row)
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+ NONE
+(1 row)
+
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ string_agg
+------------
+ 10,10
+(1 row)
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+
+(1 row)
+
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+
+(1 row)
+
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+
+(1 row)
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 1
+(1 row)
+
+-- Multiple aggregate calls in one query that share the same transition
+-- function, arguments and filter (so the planner may compute them via a
+-- single shared transition state) must still each get their own ON EMPTY
+-- default: sharing the transition state must not mean sharing (or losing)
+-- the per-aggregate ON EMPTY expression.
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ | 10
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 |
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 | 20
+(1 row)
+
+SELECT max(val, 1 ON EMPTY), max(val, 2 ON EMPTY), max(val) FROM agg_on_empty WHERE grpid = 40;
+ max | max | max
+-----+-----+-----
+ 1 | 2 |
+(1 row)
+
+-- two references to the exact same ON EMPTY aggregate call may still share
+-- everything, including the result
+SELECT sum(val, 10 ON EMPTY), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 | 10
+(1 row)
+
+-- and the same, but over non-empty input, where ON EMPTY does not fire for
+-- any of them
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum | sum
+-----+-----
+ 30 | 30
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum | sum
+-----+-----
+ 30 | 30
+(1 row)
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- with GROUP BY and empty groups: a LEFT JOIN with no match produces one
+-- row with a NULL value, not zero rows, but sum's result is NULL either
+-- way, so groups 100 and 200 get the ON EMPTY value here too
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+ g | sum
+-----+-----
+ 10 | 30
+ 20 | 30
+ 100 | -1
+ 200 | -1
+(4 rows)
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+ | 110
+(4 rows)
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+RESET enable_sort;
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+ grpid | parity | s
+-------+--------+----
+ 10 | 0 | -1
+ 10 | 1 | -1
+ 10 | | -1
+ 20 | 0 | -1
+ 20 | 1 | 30
+ 20 | | 30
+ 30 | 1 | 50
+ 30 | | 50
+ | 0 | -1
+ | 1 | 80
+ | | 80
+(11 rows)
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ sum
+-----
+ 100
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ count
+-------
+ 0
+(1 row)
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+ avg
+------
+ -999
+(1 row)
+
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+-- under a forced parallel plan: ON EMPTY must work whether or not the
+-- aggregate is parallelized (such aggregates are not partially aggregated).
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+ sum
+-----
+ -1
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+ sum
+-----
+ 30
+(1 row)
+
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+-- Error cases for ON EMPTY
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must be a constant value
+LINE 1: SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid ...
+ ^
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: invalid input syntax for type bigint: "invalid"
+LINE 1: SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE ...
+ ^
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+ERROR: ON EMPTY specified, but length is not an aggregate function
+LINE 1: SELECT length('test', 'default' ON EMPTY);
+ ^
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: cannot use subquery in ON EMPTY expression
+LINE 1: SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE...
+ ^
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must not contain a volatile function
+LINE 1: SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WH...
+ ^
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: set-returning functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_...
+ ^
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: aggregate functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE g...
+ ^
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: window functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_e...
+ ^
+-- combined with DISTINCT (should fail - not supported by the grammar)
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: syntax error at or near "ON"
+LINE 1: SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE...
+ ^
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+ percentile_cont
+-----------------
+ 15
+(1 row)
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+ pg_get_viewdef
+---------------------------------------------------------------------------------------------------------------------------------
+ SELECT percentile_cont((0.5)::double precision, '-7'::integer ON EMPTY) WITHIN GROUP (ORDER BY ((val)::double precision)) AS p+
+ FROM agg_on_empty;
+(1 row)
+
+DROP VIEW agg_on_empty_os_vw;
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+\d+ agg_on_empty_vw
+ View "public.agg_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+---------+---------+-----------+----------+---------+---------+-------------
+ grpid | integer | | | | plain |
+ total | bigint | | | | plain |
+ average | numeric | | | | main |
+ cnt | bigint | | | | plain |
+View definition:
+ SELECT grpid,
+ sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average,
+ count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty
+ GROUP BY grpid;
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+ grpid | total | average | cnt
+-------+-------+---------------------+-----
+ 10 | 30 | 15.0000000000000000 | 2
+ 20 | 30 | 30.0000000000000000 | 1
+ 30 | 50 | 50.0000000000000000 | 1
+(3 rows)
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+EXECUTE on_empty_test(40);
+ sum
+-----
+ 42
+(1 row)
+
+EXECUTE on_empty_test(10);
+ sum
+-----
+ 30
+(1 row)
+
+DEALLOCATE on_empty_test;
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+ grpid | total
+-------+-------
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- ON EMPTY is exactly COALESCE(normal_result, default_expression): it fires
+-- whenever the aggregate's ordinary result is NULL, for whatever reason --
+-- not only for a truly empty input. In particular, a non-empty group whose
+-- rows are all NULL also gets the ON EMPTY value here, because max/min's
+-- ordinary result for such a group is NULL anyway. This is exercised across
+-- the sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(max(val), -1)
+ max
+-----
+ -1
+(1 row)
+
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(min(val), -1)
+ min
+-----
+ -1
+(1 row)
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+(4 rows)
+
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+(4 rows)
+
+RESET enable_sort; RESET enable_hashagg;
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+ | 50
+(5 rows)
+
+-- Since ON EMPTY cannot distinguish "no rows at all" from "rows that
+-- happen to compute to NULL", an aggregate whose final function can
+-- legitimately return NULL from non-empty input is indistinguishable from
+-- COALESCE here too: percentile_cont's own final function returns NULL for
+-- an all-NULL, non-empty ordered set, so ON EMPTY fires for that case just
+-- as it would for a truly empty input.
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- -7, same as COALESCE(percentile_cont(...), -7)
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+-- the same COALESCE-equivalence holds for a window aggregate: ON EMPTY
+-- fires for any row whose ordinary windowed result is NULL, all-NULL frames
+-- included
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+ val | m
+-----+----
+ | -1
+ | -1
+(2 rows)
+
+-- ON EMPTY must be a constant: a correlated reference to an outer query's
+-- column is not constant and must be rejected (it is not caught by a
+-- current-level-only Var check)
+SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10;
+ERROR: ON EMPTY expression must be a constant value
+LINE 1: SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ ^
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index c0bde1c5eec..2ad169a22ed 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -6257,3 +6257,134 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
NOTICE: drop cascades to view planets_view
+-- Test ON EMPTY clause with window functions
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 | -111
+(5 rows)
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | 50
+ 2 | 20 | 30
+ 3 | 30 | 50
+ 4 | | 50
+ 5 | 50 | -222
+(5 rows)
+
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | -222
+ 2 | 20 | 10
+ 3 | 30 | 30
+ 4 | | 50
+ 5 | 50 | 30
+(5 rows)
+
+-- Two window aggregate calls with different ON EMPTY defaults, same
+-- underlying aggregate/args/frame (so they may share transition state):
+-- each must still get its own default, not one shared between them.
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER w AS d1,
+ sum(val, -222 ON EMPTY) OVER w AS d2,
+ sum(val) OVER w AS plain
+FROM win_on_empty
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
+ORDER BY id;
+ id | val | d1 | d2 | plain
+----+-----+------+------+-------
+ 1 | 10 | -111 | -222 |
+ 2 | 20 | 10 | 10 | 10
+ 3 | 30 | 20 | 20 | 20
+ 4 | | 30 | 30 | 30
+ 5 | 50 | -111 | -222 |
+(5 rows)
+
+-- Frames containing only NULL values: ON EMPTY is exactly
+-- COALESCE(normal_windowed_result, default_expression), so it fires
+-- whenever the frame's ordinary result is NULL -- which it is here, since
+-- sum/avg of an all-NULL frame is NULL regardless of frame shape.
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+ id | val | sum_current | avg_current
+----+-----+-------------+-------------
+ 4 | | -333 | -3.0
+(1 row)
+
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+-- Same COALESCE-equivalence with a growing (RANGE UNBOUNDED PRECEDING)
+-- frame instead of a sliding one: sum/avg/max are all NULL over an all-NULL
+-- partition, so ON EMPTY fires for all three here.
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+ grpid | id | val | sum_nulls | avg_nulls | max_nulls
+-------+----+-----+-----------+-----------+-----------
+ 40 | 6 | | -444 | -4.0 | -999
+ 40 | 7 | | -444 | -4.0 | -999
+(2 rows)
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+\d+ win_on_empty_vw
+ View "public.win_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+--------------+---------+-----------+----------+---------+---------+-------------
+ id | integer | | | | plain |
+ val | integer | | | | plain |
+ sum_prev_row | bigint | | | | plain |
+View definition:
+ SELECT id,
+ val,
+ sum(val, '-111'::integer ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty
+ ORDER BY id;
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 | -111
+ 6 | | 50
+ 7 | | -111
+(7 rows)
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+ERROR: ON EMPTY is not implemented for non-aggregate window functions
+LINE 1: SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_o...
+ ^
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 91f8342166f..028e525b09b 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -1786,3 +1786,225 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+
+
+-- Test ON EMPTY clause for aggregates
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- Multiple aggregate calls in one query that share the same transition
+-- function, arguments and filter (so the planner may compute them via a
+-- single shared transition state) must still each get their own ON EMPTY
+-- default: sharing the transition state must not mean sharing (or losing)
+-- the per-aggregate ON EMPTY expression.
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 10 ON EMPTY), sum(val) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT max(val, 1 ON EMPTY), max(val, 2 ON EMPTY), max(val) FROM agg_on_empty WHERE grpid = 40;
+-- two references to the exact same ON EMPTY aggregate call may still share
+-- everything, including the result
+SELECT sum(val, 10 ON EMPTY), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+-- and the same, but over non-empty input, where ON EMPTY does not fire for
+-- any of them
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+
+-- with GROUP BY and empty groups: a LEFT JOIN with no match produces one
+-- row with a NULL value, not zero rows, but sum's result is NULL either
+-- way, so groups 100 and 200 get the ON EMPTY value here too
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+RESET enable_sort;
+
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+
+-- under a forced parallel plan: ON EMPTY must work whether or not the
+-- aggregate is parallelized (such aggregates are not partially aggregated).
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+
+-- Error cases for ON EMPTY
+
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- combined with DISTINCT (should fail - not supported by the grammar)
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+DROP VIEW agg_on_empty_os_vw;
+
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+
+\d+ agg_on_empty_vw
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+
+EXECUTE on_empty_test(40);
+EXECUTE on_empty_test(10);
+
+DEALLOCATE on_empty_test;
+
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+
+-- ON EMPTY is exactly COALESCE(normal_result, default_expression): it fires
+-- whenever the aggregate's ordinary result is NULL, for whatever reason --
+-- not only for a truly empty input. In particular, a non-empty group whose
+-- rows are all NULL also gets the ON EMPTY value here, because max/min's
+-- ordinary result for such a group is NULL anyway. This is exercised across
+-- the sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(max(val), -1)
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(min(val), -1)
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+RESET enable_sort; RESET enable_hashagg;
+
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- Since ON EMPTY cannot distinguish "no rows at all" from "rows that
+-- happen to compute to NULL", an aggregate whose final function can
+-- legitimately return NULL from non-empty input is indistinguishable from
+-- COALESCE here too: percentile_cont's own final function returns NULL for
+-- an all-NULL, non-empty ordered set, so ON EMPTY fires for that case just
+-- as it would for a truly empty input.
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- -7, same as COALESCE(percentile_cont(...), -7)
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+
+-- the same COALESCE-equivalence holds for a window aggregate: ON EMPTY
+-- fires for any row whose ordinary windowed result is NULL, all-NULL frames
+-- included
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+
+-- ON EMPTY must be a constant: a correlated reference to an outer query's
+-- column is not constant and must be rejected (it is not caught by a
+-- current-level-only Var check)
+SELECT (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10;
+
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index 8e6f92d94c7..39cfec89b42 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -2301,3 +2301,73 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
+
+
+-- Test ON EMPTY clause with window functions
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+
+-- Two window aggregate calls with different ON EMPTY defaults, same
+-- underlying aggregate/args/frame (so they may share transition state):
+-- each must still get its own default, not one shared between them.
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER w AS d1,
+ sum(val, -222 ON EMPTY) OVER w AS d2,
+ sum(val) OVER w AS plain
+FROM win_on_empty
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
+ORDER BY id;
+
+-- Frames containing only NULL values: ON EMPTY is exactly
+-- COALESCE(normal_windowed_result, default_expression), so it fires
+-- whenever the frame's ordinary result is NULL -- which it is here, since
+-- sum/avg of an all-NULL frame is NULL regardless of frame shape.
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+-- Same COALESCE-equivalence with a growing (RANGE UNBOUNDED PRECEDING)
+-- frame instead of a sliding one: sum/avg/max are all NULL over an all-NULL
+-- partition, so ON EMPTY fires for all three here.
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+
+\d+ win_on_empty_vw
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
--
2.43.0
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-17 12:04 Vik Fearing <vik@postgresfriends.org>
parent: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
1 sibling, 1 reply; 14+ messages in thread
From: Vik Fearing @ 2026-09-17 12:04 UTC (permalink / raw)
To: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; pgsql-hackers; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Isaac Morland <isaac.morland@gmail.com>
On 12/09/2026 15:18, Jeevan Chalke wrote:
>
> ON EMPTY is now implemented as exactly:
>
> agg(args, default ON EMPTY) == COALESCE(agg(args), default)
I've taken a quick look at this, and I found a few bugs.
1) The first one is that the constant requirement only looks for actual
constants and not scoped constants. For example:
CREATE TABLE cust (id INTEGER, name text, def_amount PRIMARY KEY (id));
CREATE TABLE ord (id INTEGER, custid INTEGER, amount INTEGER);
INSERT INTO cust SELECT g, 'c' || g, g FROM generate_series(1, 4) AS g (g);
INSERT INTO ord VALUES (1,1,100), (2,1,50), (3,3,7);
-- rejected: "ON EMPTY expression must be a constant value"
SELECT c.id,
(SELECT SUM(o.amount, c.def_amount ON EMPTY)
FROM ord AS o
WHERE o.custid = c.id)
FROM cust AS c;
Here, the c.def_amount is constant for the subquery and should be
accepted. The example is perhaps a bit contrived, but the logic is sound.
2) Another bug I found is this:
CREATE TABLE mm (a INTEGER);
INSERT INTO mm SELECT g FROM generate_series(1, 10_000) AS g (g);
ANALYZE mm;
SELECT COALESCE(MAX(a), -1) FROM mm WHERE a > 100_000; -- -1
SELECT MAX(a, -1 ON EMPTY) FROM mm WHERE a > 100_000; -- -1
CREATE INDEX ON mm (a);
SELECT COALESCE(MAX(a), -1) FROM mm WHERE a > 100_000; -- -1
SELECT MAX(a, -1 ON EMPTY) FROM mm WHERE a > 100_000; -- NULL
When MAX and MIN get optimized with an index, the ON EMPTY seems to be
dropped.
3) The set quantifier is not recognized.
SELECT SUM(ALL a, 0 ON EMPTY) FROM t;
SELECT SUM(DISTINCT a, 0 ON EMPTY) FROM t;
Neither of those parse.
I will keep reviewing this feature.
--
Vik Fearing
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-17 13:16 Robert Haas <robertmhaas@gmail.com>
parent: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
1 sibling, 1 reply; 14+ messages in thread
From: Robert Haas @ 2026-09-17 13:16 UTC (permalink / raw)
To: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; +Cc: pgsql-hackers; Vik Fearing <vik@postgresfriends.org>; Tom Lane <tgl@sss.pgh.pa.us>; Isaac Morland <isaac.morland@gmail.com>
On Sat, Sep 12, 2026 at 9:19 AM Jeevan Chalke
<jeevan.chalke@enterprisedb.com> wrote:
> ON EMPTY is now implemented as exactly:
>
> agg(args, default ON EMPTY) == COALESCE(agg(args), default)
>
> for both plain and window aggregates: compute the aggregate's ordinary
> result exactly as without ON EMPTY, and substitute the default only if that
> result is NULL. No new expression-evaluation step, no per-row bookkeeping,
> and no restriction on partial/parallel aggregation.
This seems pretty useless -- the new syntax is more work for us to
maintain, and doesn't really add any value over just using COALESCE.
To be clear, I expect to lose this argument on the grounds that
apparently this syntax is in the spec and therefore we ought to
support it. But I don't understand why the spec -- or we -- should
spend time inventing new ways to spell existing behaviors. That just
seems confusing (and this particular choice of syntax seems
extra-confusing).
--
Robert Haas
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-17 13:31 Tom Lane <tgl@sss.pgh.pa.us>
parent: Robert Haas <robertmhaas@gmail.com>
0 siblings, 1 reply; 14+ messages in thread
From: Tom Lane @ 2026-09-17 13:31 UTC (permalink / raw)
To: Robert Haas <robertmhaas@gmail.com>; +Cc: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; pgsql-hackers; Vik Fearing <vik@postgresfriends.org>; Isaac Morland <isaac.morland@gmail.com>
Robert Haas <robertmhaas@gmail.com> writes:
> This seems pretty useless -- the new syntax is more work for us to
> maintain, and doesn't really add any value over just using COALESCE.
It could add value, in scenarios where substitute-for-NULL doesn't
give quite the behavior you want. But that's not so for the two
aggregates the spec has bothered to define this for, and I'm having
a hard time coming up with an aggregate for which it would be so.
If somebody actually did have an aggregate that could return null for
more than zero input rows, they could always do
CASE WHEN count(x) > 0 THEN frobnitz(x) ELSE value_for_zero_rows END
which has the extra benefit that you can choose "count(x)" or
"count(*)" depending on your desires for what to do with null
inputs.
> To be clear, I expect to lose this argument on the grounds that
> apparently this syntax is in the spec and therefore we ought to
> support it. But I don't understand why the spec -- or we -- should
> spend time inventing new ways to spell existing behaviors. That just
> seems confusing (and this particular choice of syntax seems
> extra-confusing).
Yes, this choice of syntax sucks pretty badly. In the COALESCE
spelling, it's crystal clear that the substitute value is not an
aggregate argument and so is evaluated at most once (per group);
there's no need for gamesmanship around restricting it to be a
constant.
I'd be totally fine with rejecting this as a frammish we do
not care to support.
regards, tom lane
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-17 15:47 Vik Fearing <vik@postgresfriends.org>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 14+ messages in thread
From: Vik Fearing @ 2026-09-17 15:47 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; Robert Haas <robertmhaas@gmail.com>; +Cc: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
On 17/09/2026 15:31, Tom Lane wrote:
> Yes, this choice of syntax sucks pretty badly.
I agree. The next edition isn't out yet, if we would like to suggest
something better.
> I'd be totally fine with rejecting this as a frammish we do
> not care to support.
I am not the most unbiased person, but I would like us to implement it.
If for nothing else, then for helping people convert from database
implementations that do have it.
--
Vik Fearing
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-17 15:55 Tom Lane <tgl@sss.pgh.pa.us>
parent: Vik Fearing <vik@postgresfriends.org>
0 siblings, 1 reply; 14+ messages in thread
From: Tom Lane @ 2026-09-17 15:55 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: Robert Haas <robertmhaas@gmail.com>; Jeevan Chalke <jeevan.chalke@enterprisedb.com>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
Vik Fearing <vik@postgresfriends.org> writes:
> On 17/09/2026 15:31, Tom Lane wrote:
>> I'd be totally fine with rejecting this as a frammish we do
>> not care to support.
> I am not the most unbiased person, but I would like us to implement it.
> If for nothing else, then for helping people convert from database
> implementations that do have it.
It's not zero cost. Robert already mentioned the
development/maintenance effort involved, and it also bloats the Bison
grammar rules, creating some incremental penalty on parsing speed.
Admittedly these costs aren't large, but neither is the benefit
of supporting it.
regards, tom lane
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-24 13:13 Jeevan Chalke <jeevan.chalke@enterprisedb.com>
parent: Vik Fearing <vik@postgresfriends.org>
0 siblings, 0 replies; 14+ messages in thread
From: Jeevan Chalke @ 2026-09-24 13:13 UTC (permalink / raw)
To: Vik Fearing <vik@postgresfriends.org>; +Cc: pgsql-hackers; Tom Lane <tgl@sss.pgh.pa.us>; Isaac Morland <isaac.morland@gmail.com>
Hi Vik,
Thanks for testing this so carefully. All three are fixed in the updated
patch:
1. Correlated outer column as default: fixed. The constant-check now only
rejects a column of the aggregate's own query level. A reference to an
outer query's column is fine now, since it can't vary across the rows
being aggregated, same as a Param. Your example now works.
2. MIN/MAX index-scan plan: fixed. That rewrite bypasses the normal
aggregate finalization, so I now exclude any aggregate with an ON
EMPTY default from it. It falls back to plain aggregation, where ON
EMPTY is applied correctly, whether or not an index exists.
3. ALL/DISTINCT syntax: fixed. Both now parse. And thinking about it more,
I could not find a real reason to disallow DISTINCT with ON EMPTY, so
it is now fully supported too, not just accepted and rejected. Dedup
happens before ON EMPTY is even considered, so they do not interfere.
Updated patch attached. Full regression suite passes, and I re-ran all
three of your examples directly against the fix.
Thanks again,
On Thu, Sep 17, 2026 at 5:34 PM Vik Fearing <vik@postgresfriends.org> wrote:
>
> On 12/09/2026 15:18, Jeevan Chalke wrote:
> >
> > ON EMPTY is now implemented as exactly:
> >
> > agg(args, default ON EMPTY) == COALESCE(agg(args), default)
>
>
> I've taken a quick look at this, and I found a few bugs.
>
>
> 1) The first one is that the constant requirement only looks for actual
> constants and not scoped constants. For example:
>
>
> CREATE TABLE cust (id INTEGER, name text, def_amount PRIMARY KEY (id));
> CREATE TABLE ord (id INTEGER, custid INTEGER, amount INTEGER);
> INSERT INTO cust SELECT g, 'c' || g, g FROM generate_series(1, 4) AS g (g);
> INSERT INTO ord VALUES (1,1,100), (2,1,50), (3,3,7);
>
> -- rejected: "ON EMPTY expression must be a constant value"
> SELECT c.id,
> (SELECT SUM(o.amount, c.def_amount ON EMPTY)
> FROM ord AS o
> WHERE o.custid = c.id)
> FROM cust AS c;
>
>
> Here, the c.def_amount is constant for the subquery and should be
> accepted. The example is perhaps a bit contrived, but the logic is sound.
>
>
> 2) Another bug I found is this:
>
>
> CREATE TABLE mm (a INTEGER);
> INSERT INTO mm SELECT g FROM generate_series(1, 10_000) AS g (g);
> ANALYZE mm;
>
> SELECT COALESCE(MAX(a), -1) FROM mm WHERE a > 100_000; -- -1
> SELECT MAX(a, -1 ON EMPTY) FROM mm WHERE a > 100_000; -- -1
>
> CREATE INDEX ON mm (a);
>
> SELECT COALESCE(MAX(a), -1) FROM mm WHERE a > 100_000; -- -1
> SELECT MAX(a, -1 ON EMPTY) FROM mm WHERE a > 100_000; -- NULL
>
> When MAX and MIN get optimized with an index, the ON EMPTY seems to be
> dropped.
>
>
> 3) The set quantifier is not recognized.
>
>
> SELECT SUM(ALL a, 0 ON EMPTY) FROM t;
> SELECT SUM(DISTINCT a, 0 ON EMPTY) FROM t;
>
>
> Neither of those parse.
>
>
> I will keep reviewing this feature.
>
> --
>
> Vik Fearing
>
>
--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*
enterprisedb.com <https://www.enterprisedb.com;
Attachments:
v3-0001-Add-support-for-ON-EMPTY-clause-in-aggregate-and-.patch (application/octet-stream, 75.8K) download
From 21c26c09483e5639d45eb46a3e2f54accb6109a2 Mon Sep 17 00:00:00 2001
From: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Date: Thu, 24 Sep 2026 17:35:54 +0530
Subject: [PATCH v3] Add support for ON EMPTY clause in aggregate and window
functions
Add an ON EMPTY clause for aggregate (and aggregate-as-window-
function) calls, returning a default when the aggregate's normal
result would otherwise be NULL:
agg(args, default ON EMPTY) == COALESCE(agg(args), default)
for both plain and window aggregates. This matches the SQL
committee's own definition of ON EMPTY for SUM/PRODUCT (per Vik
Fearing on -hackers), generalized here to arbitrary aggregates.
Implemented as a single NULL check at finalization time, after
computing the aggregate normally. No new expression step, no
per-row state, and no restriction on partial/parallel aggregation.
Since aggregates can share transition state across calls with the
same transfn/args/filter, find_compatible_agg() and ExecInitAgg()
must treat aggonempty as part of what makes two calls distinct,
and build each call's ON EMPTY state independently of that sharing.
MIN/MAX's index-scan rewrite (planagg.c) bypasses the normal Agg
node, and hence finalization, entirely, so it must exclude any
aggregate carrying an ON EMPTY default and fall back to plain
aggregation instead.
The default expression must be a constant-like expression coercible
to the aggregate's result type. It may not reference a column of
the query containing the aggregate call, nor contain aggregates,
window functions, subqueries, or volatile functions. (A reference
to an outer query's column is fine, since it cannot vary across the
rows being aggregated at the current level.) It can be combined
with ALL and DISTINCT too, and is rejected for non-aggregate window
functions; it may be used with an ordered-set (WITHIN GROUP)
aggregate, written before the WITHIN GROUP clause.
Patch also includes documentation and regression tests for
aggregates and window functions, covering empty tables, filtered
results, type coercion, all-NULL inputs, GROUP BY and grouping sets,
ordered-set aggregates, forced-parallel plans, multiple ON EMPTY
calls sharing transition state, MIN/MAX index-scan interaction, and
view deparsing.
This commit adds fields to Aggref and WindowFunc (and FuncCall).
These node types are serialized into pg_rewrite (views/rules) and
other stored expression trees, which requires a CATALOG_VERSION_NO
bump. That is omitted here to avoid conflicts with concurrent
commits; the committer should bump it at commit time.
Proposed-by: Peter Eisentraut
Jeevan Chalke
---
doc/src/sgml/syntax.sgml | 53 ++
src/backend/executor/nodeAgg.c | 22 +
src/backend/executor/nodeWindowAgg.c | 20 +
src/backend/nodes/makefuncs.c | 1 +
src/backend/nodes/nodeFuncs.c | 8 +
src/backend/optimizer/plan/planagg.c | 11 +
src/backend/optimizer/prep/prepagg.c | 3 +-
src/backend/optimizer/util/clauses.c | 6 +
src/backend/parser/gram.y | 37 ++
src/backend/parser/parse_agg.c | 140 +++++-
src/backend/parser/parse_expr.c | 11 +-
src/backend/parser/parse_func.c | 37 +-
src/backend/utils/adt/ruleutils.c | 22 +
src/include/executor/nodeAgg.h | 3 +
src/include/nodes/parsenodes.h | 1 +
src/include/nodes/primnodes.h | 5 +
src/include/parser/parse_agg.h | 4 +-
src/include/parser/parse_node.h | 1 +
src/test/regress/expected/aggregates.out | 600 +++++++++++++++++++++++
src/test/regress/expected/window.out | 131 +++++
src/test/regress/sql/aggregates.sql | 254 ++++++++++
src/test/regress/sql/window.sql | 70 +++
22 files changed, 1431 insertions(+), 9 deletions(-)
diff --git a/doc/src/sgml/syntax.sgml b/doc/src/sgml/syntax.sgml
index 67482996861..fdb2cb346f6 100644
--- a/doc/src/sgml/syntax.sgml
+++ b/doc/src/sgml/syntax.sgml
@@ -1555,6 +1555,10 @@ sqrt(2)
<primary>FILTER</primary>
</indexterm>
+ <indexterm zone="syntax-aggregates">
+ <primary>ON EMPTY</primary>
+ </indexterm>
+
<para>
An <firstterm>aggregate expression</firstterm> represents the
application of an aggregate function across the rows selected by a
@@ -1564,6 +1568,7 @@ sqrt(2)
<synopsis>
<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
+<replaceable>aggregate_name</replaceable> (<replaceable>expression</replaceable> [ , ... ] , <replaceable>default_expression</replaceable> ON EMPTY [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (ALL <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> (DISTINCT <replaceable>expression</replaceable> [ , ... ] [ <replaceable>order_by_clause</replaceable> ] ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
<replaceable>aggregate_name</replaceable> ( * ) [ FILTER ( WHERE <replaceable>filter_clause</replaceable> ) ]
@@ -1744,6 +1749,41 @@ FROM generate_series(1,10) AS s(i);
</programlisting>
</para>
+ <para>
+ If <literal>ON EMPTY</literal> is specified, then
+ <replaceable>default_expression</replaceable> supplies the value of the
+ aggregate whenever its normal result would otherwise be null; that is,
+ <literal>agg(<replaceable>args</replaceable>,
+ <replaceable>default_expression</replaceable> ON EMPTY)</literal> is
+ equivalent to <literal>COALESCE(agg(<replaceable>args</replaceable>),
+ <replaceable>default_expression</replaceable>)</literal>, including for
+ an aggregate used as a window function. In particular, this fires not
+ only for a truly empty input (no rows at all, or none passing a
+ <replaceable>filter_clause</replaceable>), but for any other reason the
+ aggregate's ordinary result happens to be null, such as a group whose
+ rows are all null, or a statistical aggregate like
+ <function>stddev</function> or <function>corr</function> returning null
+ for insufficient or degenerate data. <literal>ON EMPTY</literal> cannot
+ distinguish these cases from true emptiness. For example:
+<programlisting>
+SELECT sum(i) AS plain, sum(i, -1 ON EMPTY) AS defaulted
+FROM generate_series(1,10) AS s(i) WHERE i > 100;
+ plain | defaulted
+-------+-----------
+ | -1
+(1 row)
+</programlisting>
+ <replaceable>default_expression</replaceable> must be a constant-like
+ expression of a type coercible to the aggregate's result type: it may not
+ refer to a column of the query containing the aggregate call, nor
+ contain aggregates, window functions, subqueries, or volatile functions.
+ (A reference to a column of an <emphasis>outer</emphasis> query is
+ allowed, since it cannot vary across the rows being aggregated at the
+ current query level.) It may be combined with <literal>DISTINCT</literal>,
+ and may be used with an ordered-set aggregate, written before the
+ <literal>WITHIN GROUP</literal> clause.
+ </para>
+
<para>
The predefined aggregate functions are described in <xref
linkend="functions-aggregate"/>. Other aggregate functions can be added
@@ -1843,6 +1883,19 @@ EXCLUDE NO OTHERS
described in <xref linkend="functions-window"/>.
</para>
+ <para>
+ When an aggregate function is used as a window function, an
+ <literal>ON EMPTY</literal> clause may be given after its arguments
+ (using the same syntax as for a plain aggregate call, described in
+ <xref linkend="syntax-aggregates"/>), with the same
+ <literal>COALESCE</literal>-equivalent behavior applied per output row:
+ the <replaceable>default_expression</replaceable> is returned for any row
+ whose windowed result would otherwise be null, which includes every row
+ whose window frame contains no rows (including a frame that becomes
+ empty as the frame moves). <literal>ON EMPTY</literal> is not accepted
+ for non-aggregate window functions.
+ </para>
+
<para>
<replaceable>window_name</replaceable> is a reference to a named window
specification defined in the query's <literal>WINDOW</literal> clause.
diff --git a/src/backend/executor/nodeAgg.c b/src/backend/executor/nodeAgg.c
index 29037cf3122..28c22104799 100644
--- a/src/backend/executor/nodeAgg.c
+++ b/src/backend/executor/nodeAgg.c
@@ -1133,6 +1133,16 @@ finalize_aggregate(AggState *aggstate,
*resultIsNull = pergroupstate->transValueIsNull;
}
+ /*
+ * If an ON EMPTY default is specified and the normal result came out
+ * NULL, substitute the default -- i.e. this is exactly
+ * COALESCE(normal_result, default_expression).
+ */
+ if (peragg->aggonemptystate != NULL && *resultIsNull)
+ *resultVal = ExecEvalExpr(peragg->aggonemptystate,
+ aggstate->ss.ps.ps_ExprContext,
+ resultIsNull);
+
MemoryContextSwitchTo(oldContext);
}
@@ -4039,6 +4049,18 @@ ExecInitAgg(Agg *node, EState *estate, int eflags)
else
pertrans->aggshared = true;
ReleaseSysCache(aggTuple);
+
+ /*
+ * Build expression state for the ON EMPTY default expression. This
+ * is per-aggregate (peragg), not per-transition-state, so it must be
+ * done for every aggref even when its transition state is shared
+ * with another aggregate that already built its pertrans above.
+ */
+ if (aggref->aggonempty)
+ peragg->aggonemptystate = ExecInitExpr(aggref->aggonempty,
+ (PlanState *) aggstate);
+ else
+ peragg->aggonemptystate = NULL;
}
/*
diff --git a/src/backend/executor/nodeWindowAgg.c b/src/backend/executor/nodeWindowAgg.c
index b86dcbba055..567c542ed11 100644
--- a/src/backend/executor/nodeWindowAgg.c
+++ b/src/backend/executor/nodeWindowAgg.c
@@ -171,6 +171,9 @@ typedef struct WindowStatePerAggData
/* Data local to eval_windowaggregates() */
bool restart; /* need to restart this agg in this cycle? */
+
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} WindowStatePerAggData;
static void initialize_windowaggregate(WindowAggState *winstate,
@@ -691,6 +694,16 @@ finalize_windowaggregate(WindowAggState *winstate,
*isnull = peraggstate->transValueIsNull;
}
+ /*
+ * If an ON EMPTY default is specified and the normal result came out
+ * NULL, substitute the default -- i.e. this is exactly
+ * COALESCE(normal_result, default_expression).
+ */
+ if (peraggstate->aggonemptystate != NULL && *isnull)
+ *result = ExecEvalExpr(peraggstate->aggonemptystate,
+ winstate->ss.ps.ps_ExprContext,
+ isnull);
+
MemoryContextSwitchTo(oldContext);
}
@@ -3164,6 +3177,13 @@ initialize_peragg(WindowAggState *winstate, WindowFunc *wfunc,
&peraggstate->transtypeLen,
&peraggstate->transtypeByVal);
+ /* Build expression state for ON EMPTY default expression */
+ if (wfunc->aggonempty)
+ peraggstate->aggonemptystate = ExecInitExpr(wfunc->aggonempty,
+ (PlanState *) winstate);
+ else
+ peraggstate->aggonemptystate = NULL;
+
/*
* initval is potentially null, so don't try to access it as a struct
* field. Must do it the hard way with SysCacheGetAttr.
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index cdc02b274ff..a5e26c28a51 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -681,6 +681,7 @@ makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
n->args = args;
n->agg_order = NIL;
n->agg_filter = NULL;
+ n->agg_on_empty = NULL;
n->over = NULL;
n->agg_within_group = false;
n->agg_star = false;
diff --git a/src/backend/nodes/nodeFuncs.c b/src/backend/nodes/nodeFuncs.c
index 9512a6a824a..ecced2cfab5 100644
--- a/src/backend/nodes/nodeFuncs.c
+++ b/src/backend/nodes/nodeFuncs.c
@@ -2158,6 +2158,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
}
break;
case T_GroupingFunc:
@@ -2177,6 +2179,8 @@ expression_tree_walker_impl(Node *node,
return true;
if (WALK(expr->aggfilter))
return true;
+ if (WALK(expr->aggonempty))
+ return true;
if (WALK(expr->runCondition))
return true;
}
@@ -3041,6 +3045,7 @@ expression_tree_mutator_impl(Node *node,
MUTATE(newnode->aggorder, aggref->aggorder, List *);
MUTATE(newnode->aggdistinct, aggref->aggdistinct, List *);
MUTATE(newnode->aggfilter, aggref->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, aggref->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -3075,6 +3080,7 @@ expression_tree_mutator_impl(Node *node,
FLATCOPY(newnode, wfunc, WindowFunc);
MUTATE(newnode->args, wfunc->args, List *);
MUTATE(newnode->aggfilter, wfunc->aggfilter, Expr *);
+ MUTATE(newnode->aggonempty, wfunc->aggonempty, Expr *);
return (Node *) newnode;
}
break;
@@ -4427,6 +4433,8 @@ raw_expression_tree_walker_impl(Node *node,
return true;
if (WALK(fcall->agg_filter))
return true;
+ if (WALK(fcall->agg_on_empty))
+ return true;
if (WALK(fcall->over))
return true;
/* function name is deemed uninteresting */
diff --git a/src/backend/optimizer/plan/planagg.c b/src/backend/optimizer/plan/planagg.c
index 369d713b70a..082ee50fc8d 100644
--- a/src/backend/optimizer/plan/planagg.c
+++ b/src/backend/optimizer/plan/planagg.c
@@ -280,6 +280,17 @@ can_minmax_aggs(PlannerInfo *root, List **context)
if (aggref->aggfilter != NULL)
return false;
+ /*
+ * The generated subquery path bypasses the normal Agg node (and
+ * hence finalize_aggregate()'s ON EMPTY handling) entirely, in
+ * favor of a Limit atop an indexscan. We could teach it to apply
+ * the ON EMPTY default when the indexscan finds no matching row,
+ * but for now, just punt and let this aggregate go through the
+ * normal path, where ON EMPTY is handled correctly.
+ */
+ if (aggref->aggonempty != NULL)
+ return false;
+
aggsortop = fetch_agg_sort_op(aggref->aggfnoid);
if (!OidIsValid(aggsortop))
return false; /* not a MIN/MAX aggregate */
diff --git a/src/backend/optimizer/prep/prepagg.c b/src/backend/optimizer/prep/prepagg.c
index 3737cc15ba1..17d3a8dd474 100644
--- a/src/backend/optimizer/prep/prepagg.c
+++ b/src/backend/optimizer/prep/prepagg.c
@@ -423,7 +423,8 @@ find_compatible_agg(PlannerInfo *root, Aggref *newagg,
if (newagg->aggfnoid == existingRef->aggfnoid &&
newagg->aggtype == existingRef->aggtype &&
newagg->aggcollid == existingRef->aggcollid &&
- equal(newagg->aggdirectargs, existingRef->aggdirectargs))
+ equal(newagg->aggdirectargs, existingRef->aggdirectargs) &&
+ equal(newagg->aggonempty, existingRef->aggonempty))
{
list_free(*same_input_transnos);
*same_input_transnos = NIL;
diff --git a/src/backend/optimizer/util/clauses.c b/src/backend/optimizer/util/clauses.c
index 3e1f210652d..167abf1ac3f 100644
--- a/src/backend/optimizer/util/clauses.c
+++ b/src/backend/optimizer/util/clauses.c
@@ -2915,6 +2915,7 @@ eval_const_expressions_mutator(Node *node,
Oid funcid = expr->winfnoid;
List *args;
Expr *aggfilter;
+ Expr *aggonempty;
HeapTuple func_tuple;
WindowFunc *newexpr;
@@ -2944,6 +2945,10 @@ eval_const_expressions_mutator(Node *node,
aggfilter = (Expr *)
eval_const_expressions_mutator((Node *) expr->aggfilter,
context);
+ /* ... and the ON EMPTY expression */
+ aggonempty = (Expr *)
+ eval_const_expressions_mutator((Node *) expr->aggonempty,
+ context);
/* And build the replacement WindowFunc node */
newexpr = makeNode(WindowFunc);
@@ -2953,6 +2958,7 @@ eval_const_expressions_mutator(Node *node,
newexpr->inputcollid = expr->inputcollid;
newexpr->args = args;
newexpr->aggfilter = aggfilter;
+ newexpr->aggonempty = aggonempty;
newexpr->runCondition = expr->runCondition;
newexpr->winref = expr->winref;
newexpr->winstar = expr->winstar;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 0563453fe24..315a078bfc0 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -464,6 +464,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <list> group_by_list
%type <node> group_by_item empty_grouping_set rollup_clause cube_clause
%type <node> grouping_sets_clause
+%type <node> on_empty
%type <list> opt_fdw_options fdw_options
%type <defelt> fdw_option
@@ -16049,6 +16050,16 @@ func_application: func_name '(' ')'
n->agg_order = $7;
$$ = (Node *) n;
}
+ | func_name '(' func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $3,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $5;
+ n->agg_order = $6;
+ $$ = (Node *) n;
+ }
| func_name '(' ALL func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16062,6 +16073,16 @@ func_application: func_name '(' ')'
*/
$$ = (Node *) n;
}
+ | func_name '(' ALL func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $4,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $6;
+ n->agg_order = $7;
+ $$ = (Node *) n;
+ }
| func_name '(' DISTINCT func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16072,6 +16093,17 @@ func_application: func_name '(' ')'
n->agg_distinct = true;
$$ = (Node *) n;
}
+ | func_name '(' DISTINCT func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $4,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $6;
+ n->agg_order = $7;
+ n->agg_distinct = true;
+ $$ = (Node *) n;
+ }
| func_name '(' '*' ')'
{
/*
@@ -16094,6 +16126,11 @@ func_application: func_name '(' ')'
;
+on_empty: a_expr ON EMPTY_P
+ { $$ = $1; }
+ ;
+
+
/*
* func_expr and its cousin func_expr_windowless are split out from c_expr just
* so that we have classifications for "everything that is a function call or
diff --git a/src/backend/parser/parse_agg.c b/src/backend/parser/parse_agg.c
index a5424c9d24c..9d94ecb8a87 100644
--- a/src/backend/parser/parse_agg.c
+++ b/src/backend/parser/parse_agg.c
@@ -21,6 +21,7 @@
#include "common/int.h"
#include "nodes/makefuncs.h"
#include "nodes/nodeFuncs.h"
+#include "optimizer/clauses.h"
#include "optimizer/optimizer.h"
#include "parser/parse_agg.h"
#include "parser/parse_clause.h"
@@ -82,6 +83,9 @@ static Var *buildGroupedVar(int attnum, Index ressortgroupref,
static void check_agglevels_and_constraints(ParseState *pstate, Node *expr);
static List *expand_groupingset_node(GroupingSet *gs);
static Node *make_agg_arg(Oid argtype, Oid argcollation);
+static Node *check_agg_on_empty(ParseState *pstate, Oid aggtype,
+ Expr *agg_on_empty, int location);
+static bool agg_on_empty_contains_var_walker(Node *node, void *context);
/*
@@ -111,7 +115,8 @@ static Node *make_agg_arg(Oid argtype, Oid argcollation);
*/
void
transformAggregateCall(ParseState *pstate, Aggref *agg,
- List *args, List *aggorder, bool agg_distinct)
+ List *args, List *aggorder, bool agg_distinct,
+ Expr *agg_on_empty)
{
List *argtypes = NIL;
List *tlist = NIL;
@@ -231,6 +236,8 @@ transformAggregateCall(ParseState *pstate, Aggref *agg,
agg->args = tlist;
agg->aggorder = torder;
agg->aggdistinct = tdistinct;
+ agg->aggonempty = (Expr *) check_agg_on_empty(pstate, agg->aggtype,
+ agg_on_empty, agg->location);
/*
* Now build the aggargtypes list with the type OIDs of the direct and
@@ -499,6 +506,14 @@ check_agglevels_and_constraints(ParseState *pstate, Node *expr)
else
err = _("grouping operations are not allowed in DEFAULT expressions");
+ break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+
+ if (isAgg)
+ err = _("aggregate functions are not allowed in ON EMPTY expressions");
+ else
+ err = _("grouping operations are not allowed in ON EMPTY expressions");
+
break;
case EXPR_KIND_INDEX_EXPRESSION:
if (isAgg)
@@ -877,7 +892,7 @@ check_agg_arguments_walker(Node *node,
*/
void
transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef)
+ WindowDef *windef, Expr *agg_on_empty)
{
const char *err;
bool errkind;
@@ -988,6 +1003,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("window functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("window functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("window functions are not allowed in index expressions");
break;
@@ -1119,6 +1137,9 @@ transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
}
pstate->p_hasWindowFuncs = true;
+ wfunc->aggonempty = (Expr *) check_agg_on_empty(pstate, wfunc->wintype,
+ agg_on_empty,
+ wfunc->location);
}
/*
@@ -2403,3 +2424,118 @@ make_agg_arg(Oid argtype, Oid argcollation)
argp->location = -1;
return (Node *) argp;
}
+
+/*
+ * check_agg_on_empty -
+ * Checks the aggregate's ON EMPTY expression for correctness.
+ */
+static Node *
+check_agg_on_empty(ParseState *pstate, Oid aggtype, Expr *agg_on_empty,
+ int location)
+{
+ Oid defexprtype;
+
+ if (!agg_on_empty)
+ return NULL;
+
+ /*
+ * default expression must be a constant - it cannot contain a reference
+ * to a column of the aggregate's own query level (a Var of the current
+ * level would vary across the very rows being aggregated), nor an
+ * aggregate or window function.
+ *
+ * A reference to an outer query's column (varlevelsup > 0) is fine: it
+ * is fixed for the duration of evaluating this query, exactly like a
+ * Param or a stable function call, which are already allowed. We
+ * cannot use contain_var_clause() to make this distinction, as it does
+ * not look at varlevelsup at all; use a dedicated walker instead.
+ */
+ if (agg_on_empty_contains_var_walker((Node *) agg_on_empty, NULL))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must be a constant value"),
+ parser_errposition(pstate, location)));
+
+ if (contain_agg_clause((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain an aggregate function"),
+ parser_errposition(pstate, location)));
+
+ if (contain_windowfuncs((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a window function"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * Sub-selects are not constant and, more importantly, the ON EMPTY
+ * expression is only run through ExecInitExpr() at execution time, never
+ * the sub-plan setup that a normal target expression receives, so a
+ * sub-select here would fail (or crash) at execution. Reject it.
+ */
+ if (checkExprHasSubLink((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a subquery"),
+ parser_errposition(pstate, location)));
+
+ /*
+ * The default is evaluated only once, for the empty-input case, so a
+ * volatile expression would not behave like a per-row value. Restrict it
+ * to a stable/immutable, constant-like expression.
+ */
+ if (contain_volatile_functions((Node *) agg_on_empty))
+ ereport(ERROR,
+ (errcode(ERRCODE_INVALID_PARAMETER_VALUE),
+ errmsg("ON EMPTY expression must not contain a volatile function"),
+ parser_errposition(pstate, location)));
+
+ defexprtype = exprType((Node *) agg_on_empty);
+
+ /* default expression must be coercible to the aggregate's result type. */
+ agg_on_empty = (Expr *) coerce_to_target_type(pstate,
+ (Node *) agg_on_empty,
+ defexprtype,
+ aggtype,
+ -1,
+ COERCION_ASSIGNMENT,
+ COERCE_IMPLICIT_CAST,
+ -1);
+
+ if (agg_on_empty == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("ON EMPTY expression type %s cannot be coerced to aggregate result type %s",
+ format_type_be(defexprtype),
+ format_type_be(aggtype)),
+ parser_errposition(pstate, location)));
+
+ return (Node *) agg_on_empty;
+}
+
+/*
+ * agg_on_empty_contains_var_walker -
+ * Returns true if the node tree contains a Var of the current query
+ * level, or a CurrentOfExpr.
+ *
+ * A Var of an outer query level (varlevelsup > 0) is not reported: it is
+ * constant for the duration of evaluating the current query, just like a
+ * Param. CurrentOfExpr is always tied to the current scan, so it is
+ * rejected unconditionally. Sub-selects are rejected separately (their
+ * Query is not descended into by expression_tree_walker anyway). This runs
+ * during parse analysis, so PlaceHolderVars (which the planner introduces)
+ * cannot appear; a Var inside one would be caught by the recursion anyway.
+ */
+static bool
+agg_on_empty_contains_var_walker(Node *node, void *context)
+{
+ if (node == NULL)
+ return false;
+ if (IsA(node, Var))
+ return (((Var *) node)->varlevelsup == 0);
+ if (IsA(node, CurrentOfExpr))
+ return true;
+ return expression_tree_walker(node, agg_on_empty_contains_var_walker,
+ context);
+}
diff --git a/src/backend/parser/parse_expr.c b/src/backend/parser/parse_expr.c
index 05a6b72d4c9..55434938089 100644
--- a/src/backend/parser/parse_expr.c
+++ b/src/backend/parser/parse_expr.c
@@ -566,6 +566,7 @@ transformColumnRef(ParseState *pstate, ColumnRef *cref)
case EXPR_KIND_CHECK_CONSTRAINT:
case EXPR_KIND_DOMAIN_CHECK:
case EXPR_KIND_FUNCTION_DEFAULT:
+ case EXPR_KIND_AGG_ON_EMPTY:
case EXPR_KIND_INDEX_EXPRESSION:
case EXPR_KIND_INDEX_PREDICATE:
case EXPR_KIND_STATS_EXPRESSION:
@@ -1838,6 +1839,9 @@ transformSubLink(ParseState *pstate, SubLink *sublink)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("cannot use subquery in DEFAULT expression");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("cannot use subquery in ON EMPTY expression");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("cannot use subquery in index expression");
break;
@@ -3206,6 +3210,8 @@ ParseExprKindName(ParseExprKind exprKind)
case EXPR_KIND_COLUMN_DEFAULT:
case EXPR_KIND_FUNCTION_DEFAULT:
return "DEFAULT";
+ case EXPR_KIND_AGG_ON_EMPTY:
+ return "ON EMPTY";
case EXPR_KIND_INDEX_EXPRESSION:
return "index expression";
case EXPR_KIND_INDEX_PREDICATE:
@@ -3969,7 +3975,7 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
parser_errposition(pstate, agg_ctor->location));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, agg_ctor->over);
+ transformWindowFuncCall(pstate, wfunc, agg_ctor->over, NULL);
node = (Node *) wfunc;
}
@@ -3996,7 +4002,8 @@ transformJsonAggConstructor(ParseState *pstate, JsonAggConstructor *agg_ctor,
aggref->aggtransno = -1;
aggref->location = agg_ctor->location;
- transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order, false);
+ transformAggregateCall(pstate, aggref, args, agg_ctor->agg_order,
+ false, NULL);
node = (Node *) aggref;
}
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index f75f5f2fbba..944eaa69f26 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -95,6 +95,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
Expr *agg_filter = NULL;
+ Expr *agg_on_empty = NULL;
WindowDef *over = (fn ? fn->over : NULL);
bool agg_within_group = (fn ? fn->agg_within_group : false);
bool agg_star = (fn ? fn->agg_star : false);
@@ -130,6 +131,15 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
EXPR_KIND_FILTER,
"FILTER");
+ /*
+ * If there's an aggregate ON EMPTY default value given, transform it
+ * here. It is parsed in its own expression kind so that disallowed
+ * constructs are reported as occurring "in ON EMPTY expressions".
+ */
+ if (fn && fn->agg_on_empty != NULL)
+ agg_on_empty = (Expr *) transformExpr(pstate, fn->agg_on_empty,
+ EXPR_KIND_AGG_ON_EMPTY);
+
/*
* Most of the rest of the parser just assumes that functions do not have
* more than FUNC_MAX_ARGS parameters. We have to test here to protect
@@ -226,6 +236,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
*/
could_be_projection = (nargs == 1 && !proc_call &&
agg_order == NIL && agg_filter == NULL &&
+ agg_on_empty == NULL &&
!agg_star && !agg_distinct && over == NULL &&
!func_variadic && argnames == NIL &&
list_length(funcname) == 1 &&
@@ -339,6 +350,12 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("ORDER BY specified, but %s is not an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+ if (agg_on_empty != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("ON EMPTY specified, but %s is not an aggregate function",
+ NameListToString(funcname)),
+ parser_errposition(pstate, location)));
if (agg_filter)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
@@ -876,7 +893,8 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional aggregate-specific processing */
- transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
+ transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct,
+ agg_on_empty);
retval = (Node *) aggref;
}
@@ -951,6 +969,18 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("FILTER is not implemented for non-aggregate window functions"),
parser_errposition(pstate, location)));
+ /*
+ * ON EMPTY only has meaning for aggregates: it supplies the value to
+ * return when the aggregate processes no rows. A true window
+ * function does not aggregate input rows, so it would be silently
+ * ignored; reject it instead.
+ */
+ if (!wfunc->winagg && agg_on_empty)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("ON EMPTY is not implemented for non-aggregate window functions"),
+ parser_errposition(pstate, location)));
+
/*
* Window functions can't either take or return sets
*/
@@ -969,7 +999,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
parser_errposition(pstate, location)));
/* parse_agg.c does additional window-func-specific processing */
- transformWindowFuncCall(pstate, wfunc, over);
+ transformWindowFuncCall(pstate, wfunc, over, agg_on_empty);
retval = (Node *) wfunc;
}
@@ -2806,6 +2836,9 @@ check_srf_call_placement(ParseState *pstate, Node *last_srf, int location)
case EXPR_KIND_FUNCTION_DEFAULT:
err = _("set-returning functions are not allowed in DEFAULT expressions");
break;
+ case EXPR_KIND_AGG_ON_EMPTY:
+ err = _("set-returning functions are not allowed in ON EMPTY expressions");
+ break;
case EXPR_KIND_INDEX_EXPRESSION:
err = _("set-returning functions are not allowed in index expressions");
break;
diff --git a/src/backend/utils/adt/ruleutils.c b/src/backend/utils/adt/ruleutils.c
index 5e8e1683db0..58be7e728b7 100644
--- a/src/backend/utils/adt/ruleutils.c
+++ b/src/backend/utils/adt/ruleutils.c
@@ -10985,6 +10985,14 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
*/
Assert(!aggref->aggvariadic);
get_rule_expr((Node *) aggref->aggdirectargs, context, true);
+
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
Assert(aggref->aggorder != NIL);
appendStringInfoString(buf, ") WITHIN GROUP (ORDER BY ");
get_rule_orderby(aggref->aggorder, aggref->args, false, context);
@@ -11030,6 +11038,13 @@ get_agg_expr_helper(Aggref *aggref, deparse_context *context,
}
}
+ if (aggref->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) aggref->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (aggref->aggorder != NIL)
{
appendStringInfoString(buf, " ORDER BY ");
@@ -11130,6 +11145,13 @@ get_windowfunc_expr_helper(WindowFunc *wfunc, deparse_context *context,
get_rule_expr((Node *) wfunc->args, context, true);
}
+ if (wfunc->aggonempty != NULL)
+ {
+ appendStringInfoString(buf, ", ");
+ get_rule_expr((Node *) wfunc->aggonempty, context, false);
+ appendStringInfoString(buf, " ON EMPTY");
+ }
+
if (options)
appendStringInfoString(buf, options);
diff --git a/src/include/executor/nodeAgg.h b/src/include/executor/nodeAgg.h
index 1e1be9666ae..de3b751e30d 100644
--- a/src/include/executor/nodeAgg.h
+++ b/src/include/executor/nodeAgg.h
@@ -229,6 +229,9 @@ typedef struct AggStatePerAggData
* aggregates because the final function is read-write.
*/
bool shareable;
+
+ /* ExprState for evaluating ON EMPTY default value, or NULL */
+ ExprState *aggonemptystate;
} AggStatePerAggData;
/*
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 0debcd193ab..8ea15f5338f 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -458,6 +458,7 @@ typedef struct FuncCall
bool agg_within_group; /* ORDER BY appeared in WITHIN GROUP */
bool agg_star; /* argument was really '*' */
bool agg_distinct; /* arguments were labeled DISTINCT */
+ Node *agg_on_empty; /* user given value to use ON EMPTY set */
bool func_variadic; /* last argument was labeled VARIADIC */
CoercionForm funcformat; /* how to display this node */
ParseLoc location; /* token location, or -1 if unknown */
diff --git a/src/include/nodes/primnodes.h b/src/include/nodes/primnodes.h
index 2a832a27f49..7cb169d7738 100644
--- a/src/include/nodes/primnodes.h
+++ b/src/include/nodes/primnodes.h
@@ -497,6 +497,9 @@ typedef struct Aggref
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
+
/* true if argument list was really '*' */
bool aggstar pg_node_attr(query_jumble_ignore);
@@ -602,6 +605,8 @@ typedef struct WindowFunc
List *args;
/* FILTER expression, if any */
Expr *aggfilter;
+ /* ON EMPTY expression, if any */
+ Expr *aggonempty;
/* List of WindowFuncRunConditions to help short-circuit execution */
List *runCondition pg_node_attr(query_jumble_ignore);
/* index of associated WindowClause */
diff --git a/src/include/parser/parse_agg.h b/src/include/parser/parse_agg.h
index 8a5653798db..f93e956b83e 100644
--- a/src/include/parser/parse_agg.h
+++ b/src/include/parser/parse_agg.h
@@ -17,12 +17,12 @@
extern void transformAggregateCall(ParseState *pstate, Aggref *agg,
List *args, List *aggorder,
- bool agg_distinct);
+ bool agg_distinct, Expr *agg_on_empty);
extern Node *transformGroupingFunc(ParseState *pstate, GroupingFunc *p);
extern void transformWindowFuncCall(ParseState *pstate, WindowFunc *wfunc,
- WindowDef *windef);
+ WindowDef *windef, Expr *agg_on_empty);
extern void parseCheckAggregates(ParseState *pstate, Query *qry);
diff --git a/src/include/parser/parse_node.h b/src/include/parser/parse_node.h
index f23e21f318b..b7b7d37e4c6 100644
--- a/src/include/parser/parse_node.h
+++ b/src/include/parser/parse_node.h
@@ -69,6 +69,7 @@ typedef enum ParseExprKind
EXPR_KIND_DOMAIN_CHECK, /* CHECK constraint for a domain */
EXPR_KIND_COLUMN_DEFAULT, /* default value for a table column */
EXPR_KIND_FUNCTION_DEFAULT, /* default parameter value for function */
+ EXPR_KIND_AGG_ON_EMPTY, /* aggregate/window ON EMPTY default value */
EXPR_KIND_INDEX_EXPRESSION, /* index expression */
EXPR_KIND_INDEX_PREDICATE, /* index predicate */
EXPR_KIND_STATS_EXPRESSION, /* extended statistics expression */
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 7d07619956f..71c8abd82d0 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -3958,3 +3958,603 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+-- Test ON EMPTY clause for aggregates
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+ sum
+-----
+ -1
+(1 row)
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ -1
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+ 0
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ max
+-----
+ 999
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ min
+------
+ -999
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ count
+-------
+ 0
+(1 row)
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum
+-----
+ 30
+(1 row)
+
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ max
+-----
+ 20
+(1 row)
+
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ min
+-----
+ 10
+(1 row)
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+ NONE
+(1 row)
+
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ string_agg
+------------
+ 10,10
+(1 row)
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+
+(1 row)
+
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ avg
+-----
+
+(1 row)
+
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ string_agg
+------------
+
+(1 row)
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 1
+(1 row)
+
+-- Multiple aggregate calls in one query that share the same transition
+-- function, arguments and filter (so the planner may compute them via a
+-- single shared transition state) must still each get their own ON EMPTY
+-- default: sharing the transition state must not mean sharing (or losing)
+-- the per-aggregate ON EMPTY expression.
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ | 10
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 |
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 | 20
+(1 row)
+
+SELECT max(val, 1 ON EMPTY), max(val, 2 ON EMPTY), max(val) FROM agg_on_empty WHERE grpid = 40;
+ max | max | max
+-----+-----+-----
+ 1 | 2 |
+(1 row)
+
+-- two references to the exact same ON EMPTY aggregate call may still share
+-- everything, including the result
+SELECT sum(val, 10 ON EMPTY), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum | sum
+-----+-----
+ 10 | 10
+(1 row)
+
+-- and the same, but over non-empty input, where ON EMPTY does not fire for
+-- any of them
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum | sum
+-----+-----
+ 30 | 30
+(1 row)
+
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum | sum
+-----+-----
+ 30 | 30
+(1 row)
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- with GROUP BY and empty groups: a LEFT JOIN with no match produces one
+-- row with a NULL value, not zero rows, but sum's result is NULL either
+-- way, so groups 100 and 200 get the ON EMPTY value here too
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+ g | sum
+-----+-----
+ 10 | 30
+ 20 | 30
+ 100 | -1
+ 200 | -1
+(4 rows)
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | 30
+ 20 | 30
+ 30 | 50
+ | 110
+(4 rows)
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+ grpid | sum
+-------+-----
+ 10 | -1
+ 20 | 30
+ 30 | 50
+ | 80
+(4 rows)
+
+RESET enable_sort;
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+ grpid | parity | s
+-------+--------+----
+ 10 | 0 | -1
+ 10 | 1 | -1
+ 10 | | -1
+ 20 | 0 | -1
+ 20 | 1 | 30
+ 20 | | 30
+ 30 | 1 | 50
+ 30 | | 50
+ | 0 | -1
+ | 1 | 80
+ | | 80
+(11 rows)
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ sum
+-----
+ 100
+(1 row)
+
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+ count
+-------
+ 0
+(1 row)
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+ avg
+------
+ -999
+(1 row)
+
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+ avg
+---------------------
+ 15.0000000000000000
+(1 row)
+
+-- under a forced parallel plan: ON EMPTY must give the same answer whether
+-- or not the aggregate ends up partially/parallel aggregated, since the
+-- COALESCE-equivalent check happens once, centrally, at finalization.
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+ sum
+-----
+ -1
+(1 row)
+
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+ sum
+-----
+ 30
+(1 row)
+
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+-- MIN/MAX over an indexed column can be rewritten by the planner into an
+-- index-scan-based plan (see planagg.c) that bypasses the normal Agg node,
+-- and hence finalize_aggregate(), entirely. An aggregate carrying an ON
+-- EMPTY default must be excluded from that rewrite so its default still
+-- applies; verify both the plan shape and the result. Needs enough rows
+-- (and a matching index) for the planner to actually prefer that rewrite.
+CREATE TABLE agg_on_empty_mm(a int);
+INSERT INTO agg_on_empty_mm SELECT g FROM generate_series(1, 10000) g;
+CREATE INDEX ON agg_on_empty_mm (a);
+ANALYZE agg_on_empty_mm;
+-- plain max/min (no ON EMPTY): uses the index-scan/Limit rewrite
+EXPLAIN (COSTS OFF)
+ SELECT max(a) FROM agg_on_empty_mm WHERE a > 100000;
+ QUERY PLAN
+---------------------------------------------------------------------------------------
+ Result
+ Replaces: MinMaxAggregate
+ InitPlan minmax_1
+ -> Limit
+ -> Index Only Scan Backward using agg_on_empty_mm_a_idx on agg_on_empty_mm
+ Index Cond: ((a IS NOT NULL) AND (a > 100000))
+(6 rows)
+
+SELECT max(a) FROM agg_on_empty_mm WHERE a > 100000;
+ max
+-----
+
+(1 row)
+
+-- with ON EMPTY: must not use that rewrite, so the default still applies
+EXPLAIN (COSTS OFF)
+ SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+ QUERY PLAN
+----------------------------------------------------------------------
+ Aggregate
+ -> Index Only Scan using agg_on_empty_mm_a_idx on agg_on_empty_mm
+ Index Cond: (a > 100000)
+(3 rows)
+
+SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+ max
+-----
+ -1
+(1 row)
+
+SELECT min(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+ min
+-----
+ -1
+(1 row)
+
+DROP TABLE agg_on_empty_mm;
+-- Error cases for ON EMPTY
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must be a constant value
+LINE 1: SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid ...
+ ^
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: invalid input syntax for type bigint: "invalid"
+LINE 1: SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE ...
+ ^
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+ERROR: ON EMPTY specified, but length is not an aggregate function
+LINE 1: SELECT length('test', 'default' ON EMPTY);
+ ^
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: cannot use subquery in ON EMPTY expression
+LINE 1: SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE...
+ ^
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: ON EMPTY expression must not contain a volatile function
+LINE 1: SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WH...
+ ^
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: set-returning functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_...
+ ^
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: aggregate functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE g...
+ ^
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ERROR: window functions are not allowed in ON EMPTY expressions
+LINE 1: SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_e...
+ ^
+-- combined with DISTINCT: dedup happens upstream of finalization, entirely
+-- independent of ON EMPTY, so both work together with no special-casing
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- empty -> 0
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM (VALUES (5), (5), (10)) v(val); -- 15, not 20
+ sum
+-----
+ 15
+(1 row)
+
+-- ALL is fine with ON EMPTY (it is the default quantifier anyway)
+SELECT sum(ALL val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+ sum
+-----
+ 0
+(1 row)
+
+SELECT sum(ALL val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+ sum
+-----
+ 30
+(1 row)
+
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+ percentile_cont
+-----------------
+ 15
+(1 row)
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+ pg_get_viewdef
+---------------------------------------------------------------------------------------------------------------------------------
+ SELECT percentile_cont((0.5)::double precision, '-7'::integer ON EMPTY) WITHIN GROUP (ORDER BY ((val)::double precision)) AS p+
+ FROM agg_on_empty;
+(1 row)
+
+DROP VIEW agg_on_empty_os_vw;
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+\d+ agg_on_empty_vw
+ View "public.agg_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+---------+---------+-----------+----------+---------+---------+-------------
+ grpid | integer | | | | plain |
+ total | bigint | | | | plain |
+ average | numeric | | | | main |
+ cnt | bigint | | | | plain |
+View definition:
+ SELECT grpid,
+ sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average,
+ count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty
+ GROUP BY grpid;
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+ grpid | total | average | cnt
+-------+-------+---------------------+-----
+ 10 | 30 | 15.0000000000000000 | 2
+ 20 | 30 | 30.0000000000000000 | 1
+ 30 | 50 | 50.0000000000000000 | 1
+(3 rows)
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+EXECUTE on_empty_test(40);
+ sum
+-----
+ 42
+(1 row)
+
+EXECUTE on_empty_test(10);
+ sum
+-----
+ 30
+(1 row)
+
+DEALLOCATE on_empty_test;
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+ grpid | total
+-------+-------
+ 10 | 30
+ 20 | 30
+ 30 | 50
+(3 rows)
+
+-- ON EMPTY is exactly COALESCE(normal_result, default_expression): it fires
+-- whenever the aggregate's ordinary result is NULL, for whatever reason --
+-- not only for a truly empty input. In particular, a non-empty group whose
+-- rows are all NULL also gets the ON EMPTY value here, because max/min's
+-- ordinary result for such a group is NULL anyway. This is exercised across
+-- the sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(max(val), -1)
+ max
+-----
+ -1
+(1 row)
+
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(min(val), -1)
+ min
+-----
+ -1
+(1 row)
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+(4 rows)
+
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+(4 rows)
+
+RESET enable_sort; RESET enable_hashagg;
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+ grpid | max
+-------+-----
+ 10 | 20
+ 20 | 30
+ 30 | 50
+ 50 | -1
+ | 50
+(5 rows)
+
+-- Since ON EMPTY cannot distinguish "no rows at all" from "rows that
+-- happen to compute to NULL", an aggregate whose final function can
+-- legitimately return NULL from non-empty input is indistinguishable from
+-- COALESCE here too: percentile_cont's own final function returns NULL for
+-- an all-NULL, non-empty ordered set, so ON EMPTY fires for that case just
+-- as it would for a truly empty input.
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- -7, same as COALESCE(percentile_cont(...), -7)
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+ percentile_cont
+-----------------
+ -7
+(1 row)
+
+-- the same COALESCE-equivalence holds for a window aggregate: ON EMPTY
+-- fires for any row whose ordinary windowed result is NULL, all-NULL frames
+-- included
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+ val | m
+-----+----
+ | -1
+ | -1
+(2 rows)
+
+-- ON EMPTY must be a constant with respect to the aggregate's own query
+-- level, but a reference to an outer query's column is fine: it cannot vary
+-- across the rows being aggregated at the current level, exactly like a
+-- Param. It is re-evaluated (and can differ) once per outer row.
+SELECT id, val, (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10 ORDER BY id;
+ id | val | max
+----+-----+-----
+ 1 | 10 | 10
+ 2 | 20 | 20
+(2 rows)
+
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/expected/window.out b/src/test/regress/expected/window.out
index c0bde1c5eec..2ad169a22ed 100644
--- a/src/test/regress/expected/window.out
+++ b/src/test/regress/expected/window.out
@@ -6257,3 +6257,134 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
NOTICE: drop cascades to view planets_view
+-- Test ON EMPTY clause with window functions
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 | -111
+(5 rows)
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | 50
+ 2 | 20 | 30
+ 3 | 30 | 50
+ 4 | | 50
+ 5 | 50 | -222
+(5 rows)
+
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+ id | val | sum_following
+----+-----+---------------
+ 1 | 10 | -222
+ 2 | 20 | 10
+ 3 | 30 | 30
+ 4 | | 50
+ 5 | 50 | 30
+(5 rows)
+
+-- Two window aggregate calls with different ON EMPTY defaults, same
+-- underlying aggregate/args/frame (so they may share transition state):
+-- each must still get its own default, not one shared between them.
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER w AS d1,
+ sum(val, -222 ON EMPTY) OVER w AS d2,
+ sum(val) OVER w AS plain
+FROM win_on_empty
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
+ORDER BY id;
+ id | val | d1 | d2 | plain
+----+-----+------+------+-------
+ 1 | 10 | -111 | -222 |
+ 2 | 20 | 10 | 10 | 10
+ 3 | 30 | 20 | 20 | 20
+ 4 | | 30 | 30 | 30
+ 5 | 50 | -111 | -222 |
+(5 rows)
+
+-- Frames containing only NULL values: ON EMPTY is exactly
+-- COALESCE(normal_windowed_result, default_expression), so it fires
+-- whenever the frame's ordinary result is NULL -- which it is here, since
+-- sum/avg of an all-NULL frame is NULL regardless of frame shape.
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+ id | val | sum_current | avg_current
+----+-----+-------------+-------------
+ 4 | | -333 | -3.0
+(1 row)
+
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+-- Same COALESCE-equivalence with a growing (RANGE UNBOUNDED PRECEDING)
+-- frame instead of a sliding one: sum/avg/max are all NULL over an all-NULL
+-- partition, so ON EMPTY fires for all three here.
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+ grpid | id | val | sum_nulls | avg_nulls | max_nulls
+-------+----+-----+-----------+-----------+-----------
+ 40 | 6 | | -444 | -4.0 | -999
+ 40 | 7 | | -444 | -4.0 | -999
+(2 rows)
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+\d+ win_on_empty_vw
+ View "public.win_on_empty_vw"
+ Column | Type | Collation | Nullable | Default | Storage | Description
+--------------+---------+-----------+----------+---------+---------+-------------
+ id | integer | | | | plain |
+ val | integer | | | | plain |
+ sum_prev_row | bigint | | | | plain |
+View definition:
+ SELECT id,
+ val,
+ sum(val, '-111'::integer ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty
+ ORDER BY id;
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+ id | val | sum_prev_row
+----+-----+--------------
+ 1 | 10 | -111
+ 2 | 20 | 10
+ 3 | 30 | 20
+ 4 | | 30
+ 5 | 50 | -111
+ 6 | | 50
+ 7 | | -111
+(7 rows)
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+ERROR: ON EMPTY is not implemented for non-aggregate window functions
+LINE 1: SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_o...
+ ^
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 91f8342166f..70686aebebc 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -1786,3 +1786,257 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+
+
+-- Test ON EMPTY clause for aggregates
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE agg_on_empty(id int, val int, grpid int);
+
+-- with empty table
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty;
+
+INSERT INTO agg_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- basic ON EMPTY tests with numeric default
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT count(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-empty result set (should use actual aggregate result)
+SELECT sum(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT avg(val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT max(val, 999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT min(val, -999 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with string default
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', 'NONE' ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with NULL default
+SELECT sum(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT string_agg(grpid::text, ',', NULL ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type coercion (integer to numeric)
+SELECT sum(val::numeric, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 0.5 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- Multiple aggregate calls in one query that share the same transition
+-- function, arguments and filter (so the planner may compute them via a
+-- single shared transition state) must still each get their own ON EMPTY
+-- default: sharing the transition state must not mean sharing (or losing)
+-- the per-aggregate ON EMPTY expression.
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 10 ON EMPTY), sum(val) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT max(val, 1 ON EMPTY), max(val, 2 ON EMPTY), max(val) FROM agg_on_empty WHERE grpid = 40;
+-- two references to the exact same ON EMPTY aggregate call may still share
+-- everything, including the result
+SELECT sum(val, 10 ON EMPTY), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+-- and the same, but over non-empty input, where ON EMPTY does not fire for
+-- any of them
+SELECT sum(val), sum(val, 10 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+SELECT sum(val, 10 ON EMPTY), sum(val, 20 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- with GROUP BY
+SELECT grpid, sum(val, 0 ON EMPTY) FROM agg_on_empty GROUP BY grpid ORDER BY grpid;
+
+-- with GROUP BY and empty groups: a LEFT JOIN with no match produces one
+-- row with a NULL value, not zero rows, but sum's result is NULL either
+-- way, so groups 100 and 200 get the ON EMPTY value here too
+SELECT g, sum(val, -1 ON EMPTY) FROM (VALUES (100), (200), (10), (20)) AS groups(g)
+ LEFT JOIN agg_on_empty ON groups.g = agg_on_empty.grpid
+ GROUP BY g ORDER BY g;
+
+-- with grouping sets: per-group state is reset across grouping-set phases, so
+-- ON EMPTY must not fire spuriously for groups that do have rows
+SELECT grpid, sum(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- with grouping sets where a FILTER empties one group: ON EMPTY fires only for
+-- that group (checked under both sorted and hashed grouping-set execution)
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+SET enable_sort = off;
+SELECT grpid, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) FROM agg_on_empty
+ GROUP BY GROUPING SETS ((grpid), ()) ORDER BY grpid;
+RESET enable_sort;
+
+-- multi-dimensional CUBE with a FILTER: ON EMPTY fires independently for each
+-- empty cell (including sub-aggregates), while populated cells return real sums
+SELECT grpid, id % 2 AS parity, sum(val, -1 ON EMPTY) FILTER (WHERE val > 25) AS s
+ FROM agg_on_empty GROUP BY CUBE(grpid, id % 2) ORDER BY grpid, parity;
+
+-- with FILTER clause
+SELECT sum(val, 100 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+SELECT count(val, 0 ON EMPTY) FILTER (WHERE val > 100) FROM agg_on_empty;
+
+-- with ORDER BY in aggregate
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 40;
+SELECT avg(val, -999 ON EMPTY ORDER BY val) FROM agg_on_empty WHERE grpid = 10;
+
+-- under a forced parallel plan: ON EMPTY must give the same answer whether
+-- or not the aggregate ends up partially/parallel aggregated, since the
+-- COALESCE-equivalent check happens once, centrally, at finalization.
+SET max_parallel_workers_per_gather = 4;
+SET parallel_setup_cost = 0;
+SET parallel_tuple_cost = 0;
+SET min_parallel_table_scan_size = 0;
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- default
+SELECT sum(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 10; -- real result
+RESET max_parallel_workers_per_gather;
+RESET parallel_setup_cost;
+RESET parallel_tuple_cost;
+RESET min_parallel_table_scan_size;
+
+-- MIN/MAX over an indexed column can be rewritten by the planner into an
+-- index-scan-based plan (see planagg.c) that bypasses the normal Agg node,
+-- and hence finalize_aggregate(), entirely. An aggregate carrying an ON
+-- EMPTY default must be excluded from that rewrite so its default still
+-- applies; verify both the plan shape and the result. Needs enough rows
+-- (and a matching index) for the planner to actually prefer that rewrite.
+CREATE TABLE agg_on_empty_mm(a int);
+INSERT INTO agg_on_empty_mm SELECT g FROM generate_series(1, 10000) g;
+CREATE INDEX ON agg_on_empty_mm (a);
+ANALYZE agg_on_empty_mm;
+
+-- plain max/min (no ON EMPTY): uses the index-scan/Limit rewrite
+EXPLAIN (COSTS OFF)
+ SELECT max(a) FROM agg_on_empty_mm WHERE a > 100000;
+SELECT max(a) FROM agg_on_empty_mm WHERE a > 100000;
+
+-- with ON EMPTY: must not use that rewrite, so the default still applies
+EXPLAIN (COSTS OFF)
+ SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+SELECT min(a, -1 ON EMPTY) FROM agg_on_empty_mm WHERE a > 100000;
+
+DROP TABLE agg_on_empty_mm;
+
+-- Error cases for ON EMPTY
+
+-- with complex expressions (should fail - must be constant)
+SELECT sum(val, val ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with type mismatch (should fail)
+SELECT sum(val, 'invalid' ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with non-aggregate function (should fail)
+SELECT length('test', 'default' ON EMPTY);
+
+-- with a subquery (should fail)
+SELECT sum(val, (SELECT 1) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a volatile function (should fail)
+SELECT sum(val, random()::int ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a set-returning function (should fail)
+SELECT sum(val, generate_series(1, 2) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a nested aggregate (should fail)
+SELECT sum(val, sum(val) ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- with a window function (should fail)
+SELECT sum(val, row_number() OVER () ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+
+-- combined with DISTINCT: dedup happens upstream of finalization, entirely
+-- independent of ON EMPTY, so both work together with no special-casing
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40; -- empty -> 0
+SELECT sum(DISTINCT val, 0 ON EMPTY) FROM (VALUES (5), (5), (10)) v(val); -- 15, not 20
+
+-- ALL is fine with ON EMPTY (it is the default quantifier anyway)
+SELECT sum(ALL val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 40;
+SELECT sum(ALL val, 0 ON EMPTY) FROM agg_on_empty WHERE grpid = 10;
+
+-- combined with an ordered-set aggregate (WITHIN GROUP): the ON EMPTY value
+-- is written before WITHIN GROUP and is returned for an empty input set
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 40; -- empty -> default
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 10; -- real result
+
+-- and it round-trips through view deparsing
+CREATE VIEW agg_on_empty_os_vw AS
+ SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val) AS p
+ FROM agg_on_empty;
+SELECT pg_get_viewdef('agg_on_empty_os_vw');
+DROP VIEW agg_on_empty_os_vw;
+
+-- deparsing of ON EMPTY in views
+CREATE VIEW agg_on_empty_vw AS
+ SELECT grpid, sum(val, 0 ON EMPTY ORDER BY val) AS total,
+ avg(val, 0 ON EMPTY) AS average, count(val, 0 ON EMPTY) AS cnt
+ FROM agg_on_empty GROUP BY grpid;
+
+\d+ agg_on_empty_vw
+
+SELECT * FROM agg_on_empty_vw ORDER BY grpid;
+
+-- with prepared statements (must use literal constants)
+PREPARE on_empty_test(int) AS
+ SELECT sum(val, 42 ON EMPTY) FROM agg_on_empty WHERE grpid = $1;
+
+EXECUTE on_empty_test(40);
+EXECUTE on_empty_test(10);
+
+DEALLOCATE on_empty_test;
+
+-- with HAVING clause
+SELECT grpid, sum(val, 0 ON EMPTY) AS total FROM agg_on_empty
+ GROUP BY grpid HAVING sum(val, 0 ON EMPTY) > 20 ORDER BY grpid;
+
+-- ON EMPTY is exactly COALESCE(normal_result, default_expression): it fires
+-- whenever the aggregate's ordinary result is NULL, for whatever reason --
+-- not only for a truly empty input. In particular, a non-empty group whose
+-- rows are all NULL also gets the ON EMPTY value here, because max/min's
+-- ordinary result for such a group is NULL anyway. This is exercised across
+-- the sorted, hashed and grouping-set execution paths.
+INSERT INTO agg_on_empty VALUES (6, NULL, 50), (7, NULL, 50);
+
+SELECT max(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(max(val), -1)
+SELECT min(val, -1 ON EMPTY) FROM agg_on_empty WHERE grpid = 50; -- -1, same as COALESCE(min(val), -1)
+
+-- and per group, under both sorted and hashed aggregation
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+SET enable_sort = off; SET enable_hashagg = on;
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY grpid ORDER BY grpid;
+RESET enable_sort; RESET enable_hashagg;
+
+-- and under grouping sets
+SELECT grpid, max(val, -1 ON EMPTY) FROM agg_on_empty
+ GROUP BY ROLLUP(grpid) ORDER BY grpid;
+
+-- Since ON EMPTY cannot distinguish "no rows at all" from "rows that
+-- happen to compute to NULL", an aggregate whose final function can
+-- legitimately return NULL from non-empty input is indistinguishable from
+-- COALESCE here too: percentile_cont's own final function returns NULL for
+-- an all-NULL, non-empty ordered set, so ON EMPTY fires for that case just
+-- as it would for a truly empty input.
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 50; -- -7, same as COALESCE(percentile_cont(...), -7)
+SELECT percentile_cont(0.5, -7 ON EMPTY) WITHIN GROUP (ORDER BY val)
+ FROM agg_on_empty WHERE grpid = 60; -- empty -> -7
+
+-- the same COALESCE-equivalence holds for a window aggregate: ON EMPTY
+-- fires for any row whose ordinary windowed result is NULL, all-NULL frames
+-- included
+SELECT val, max(val, -1 ON EMPTY) OVER () AS m
+ FROM agg_on_empty WHERE grpid = 50 ORDER BY id;
+
+-- ON EMPTY must be a constant with respect to the aggregate's own query
+-- level, but a reference to an outer query's column is fine: it cannot vary
+-- across the rows being aggregated at the current level, exactly like a
+-- Param. It is re-evaluated (and can differ) once per outer row.
+SELECT id, val, (SELECT max(inner_t.val, agg_on_empty.val ON EMPTY)
+ FROM agg_on_empty inner_t WHERE false)
+ FROM agg_on_empty WHERE grpid = 10 ORDER BY id;
+
+-- clean up
+DROP VIEW agg_on_empty_vw;
+DROP TABLE agg_on_empty;
diff --git a/src/test/regress/sql/window.sql b/src/test/regress/sql/window.sql
index 8e6f92d94c7..39cfec89b42 100644
--- a/src/test/regress/sql/window.sql
+++ b/src/test/regress/sql/window.sql
@@ -2301,3 +2301,73 @@ SELECT last_value FROM null_treatment_seq;
--cleanup
DROP TABLE planets CASCADE;
+
+
+-- Test ON EMPTY clause with window functions
+
+-- create a test table for ON EMPTY tests
+CREATE TABLE win_on_empty(id int, val int, grpid int);
+INSERT INTO win_on_empty VALUES (1, 10, 10), (2, 20, 10), (3, 30, 20), (4, NULL, 20), (5, 50, 30);
+
+-- Empty frames using ROWS (ON EMPTY value WILL be returned)
+-- On first row, "1 PRECEDING" frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+FROM win_on_empty ORDER BY id;
+
+-- Empty frames using ROWS FOLLOWING (ON EMPTY value WILL be returned)
+-- On last rows, FOLLOWING frame is empty - should return ON EMPTY value
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id ASC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+SELECT id, val,
+ sum(val, -222 ON EMPTY) OVER (ORDER BY id DESC ROWS BETWEEN 1 FOLLOWING AND 2 FOLLOWING) AS sum_following
+FROM win_on_empty ORDER BY id;
+
+-- Two window aggregate calls with different ON EMPTY defaults, same
+-- underlying aggregate/args/frame (so they may share transition state):
+-- each must still get its own default, not one shared between them.
+SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER w AS d1,
+ sum(val, -222 ON EMPTY) OVER w AS d2,
+ sum(val) OVER w AS plain
+FROM win_on_empty
+WINDOW w AS (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING)
+ORDER BY id;
+
+-- Frames containing only NULL values: ON EMPTY is exactly
+-- COALESCE(normal_windowed_result, default_expression), so it fires
+-- whenever the frame's ordinary result is NULL -- which it is here, since
+-- sum/avg of an all-NULL frame is NULL regardless of frame shape.
+SELECT id, val,
+ sum(val, -333 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS sum_current,
+ avg(val, -3.0 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN CURRENT ROW AND CURRENT ROW) AS avg_current
+FROM win_on_empty WHERE id = 4 ORDER BY id;
+
+-- Add more rows with NULLs to demonstrate
+INSERT INTO win_on_empty VALUES (6, NULL, 40), (7, NULL, 40);
+-- Same COALESCE-equivalence with a growing (RANGE UNBOUNDED PRECEDING)
+-- frame instead of a sliding one: sum/avg/max are all NULL over an all-NULL
+-- partition, so ON EMPTY fires for all three here.
+SELECT grpid, id, val,
+ sum(val, -444 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as sum_nulls,
+ avg(val, -4.0 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as avg_nulls,
+ max(val, -999 ON EMPTY) OVER (PARTITION BY grpid ORDER BY id) as max_nulls
+FROM win_on_empty WHERE grpid = 40 ORDER BY id;
+
+CREATE VIEW win_on_empty_vw AS
+ SELECT id, val,
+ sum(val, -111 ON EMPTY) OVER (ORDER BY id ROWS BETWEEN 1 PRECEDING AND 1 PRECEDING) AS sum_prev_row
+ FROM win_on_empty ORDER BY id;
+
+\d+ win_on_empty_vw
+
+SELECT * FROM win_on_empty_vw ORDER BY id;
+
+-- ON EMPTY is only meaningful for aggregates; reject it for non-aggregate
+-- window functions (should fail)
+SELECT lag(val, 1, 0 ON EMPTY) OVER (ORDER BY id) FROM win_on_empty;
+
+-- clean up
+DROP VIEW win_on_empty_vw;
+DROP TABLE win_on_empty;
--
2.43.0
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-24 13:17 Jeevan Chalke <jeevan.chalke@enterprisedb.com>
parent: Tom Lane <tgl@sss.pgh.pa.us>
0 siblings, 1 reply; 14+ messages in thread
From: Jeevan Chalke @ 2026-09-24 13:17 UTC (permalink / raw)
To: Tom Lane <tgl@sss.pgh.pa.us>; +Cc: Vik Fearing <vik@postgresfriends.org>; Robert Haas <robertmhaas@gmail.com>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
Hi Robert, Tom, Vik,
On Thu, Sep 17, 2026 at 9:25 PM Tom Lane <tgl@sss.pgh.pa.us> wrote:
> Vik Fearing <vik@postgresfriends.org> writes:
> > On 17/09/2026 15:31, Tom Lane wrote:
> >> I'd be totally fine with rejecting this as a frammish we do
> >> not care to support.
>
> > I am not the most unbiased person, but I would like us to implement it.
> > If for nothing else, then for helping people convert from database
> > implementations that do have it.
>
> It's not zero cost. Robert already mentioned the
> development/maintenance effort involved, and it also bloats the Bison
> grammar rules, creating some incremental penalty on parsing speed.
> Admittedly these costs aren't large, but neither is the benefit
> of supporting it.
>
Following up on the "is this worth it" question. I agree with Robert and
Tom: as I built it, ON EMPTY is exactly COALESCE(agg(...), default),
always, for any aggregate. I could not find a case where it gives a
different answer than COALESCE. So the general version does not add
real value over COALESCE, and I will not argue that point further.
But I think there is a much smaller version worth considering, and I
built it to check, instead of just guessing. Patch attached.
It only accepts ON EMPTY on sum() and product(), the two aggregates the
standard actually defines this for. At parse time, once we know the
call is sum() or product(), it is just rewritten to
COALESCE(sum(expr), default). Nothing else changes:
- no new field on Aggref or WindowFunc
- no executor changes
- no CATALOG_VERSION_NO bump
- no special case in the MIN/MAX index-scan code
- DISTINCT and ALL work with no extra code, since dedup happens
before the rewrite even runs
Total diff is about 110 lines (grammar, one FuncCall field, parser),
under 150 with tests. I ran the full regression suite and some manual
dump/restore checks: it all works, though view/rule dumps show the
COALESCE rewrite, not the original ON EMPTY spelling, since the
rewrite happens before anything gets stored. Text-body SQL functions
still show the original spelling, since those store raw text.
Vik, I think this still gives you what you wanted for migration: the
two aggregates the standard defines this for now match it exactly,
just spelled the standard way.
Thoughts?
Thanks,
>
> regards, tom lane
>
--
*Jeevan Chalke*
*Senior Principal Engineer, Engineering Manager*
*Product Development*
enterprisedb.com <https://www.enterprisedb.com;
Attachments:
nocfbot-wip-Minimal-ON-EMPTY-sum-product-only-rewritten-to.patch (application/octet-stream, 13.7K) download
From 0fb7f38c1a885d2d9aebf4f55b843ddb2aa1a70d Mon Sep 17 00:00:00 2001
From: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
Date: Tue, 22 Sep 2026 19:28:10 +0530
Subject: [PATCH v3wip] Minimal ON EMPTY: sum()/product() only, rewritten to
COALESCE
Alternative, much smaller take on the ON EMPTY clause discussed
on -hackers, scoped to exactly what the SQL standard defines it
for. Grammar accepts:
sum(expr, default ON EMPTY)
product(expr, default ON EMPTY)
with ALL/DISTINCT variants too. At parse time, once we know the
call is sum() or product(), it is rewritten straight into
COALESCE(sum(expr), default)
and the original Aggref is otherwise completely unmodified: no
aggonempty field, no new Aggref/WindowFunc/FuncCall payload beyond
a single transient FuncCall field used only during parsing, no
executor changes, no interaction with DISTINCT/ALL (they work for
free, since dedup happens upstream of the rewrite), no planagg.c
carve-out needed, and no CATALOG_VERSION_NO bump.
Tradeoffs versus the general patch, both deliberate for this
scoped-down version:
- Only sum() and product() are accepted; anything else errors
with a clear message. Window function usage is rejected too.
- View/rule deparsing shows the COALESCE rewrite, not the
original ON EMPTY spelling, since the rewrite happens before
the call is ever stored as an Aggref.
Total diff: under 150 lines across grammar, node definition, and
parser. Full regression suite (240 tests) passes.
Jeevan Chalke
Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
---
src/backend/nodes/makefuncs.c | 1 +
src/backend/parser/gram.y | 37 ++++++++++++
src/backend/parser/parse_func.c | 73 ++++++++++++++++++++++++
src/include/nodes/parsenodes.h | 1 +
src/test/regress/expected/aggregates.out | 65 +++++++++++++++++++++
src/test/regress/sql/aggregates.sql | 36 ++++++++++++
6 files changed, 213 insertions(+)
diff --git a/src/backend/nodes/makefuncs.c b/src/backend/nodes/makefuncs.c
index cdc02b274ff..6ca9db4a3a3 100644
--- a/src/backend/nodes/makefuncs.c
+++ b/src/backend/nodes/makefuncs.c
@@ -680,6 +680,7 @@ makeFuncCall(List *name, List *args, CoercionForm funcformat, int location)
n->funcname = name;
n->args = args;
n->agg_order = NIL;
+ n->agg_on_empty = NULL;
n->agg_filter = NULL;
n->over = NULL;
n->agg_within_group = false;
diff --git a/src/backend/parser/gram.y b/src/backend/parser/gram.y
index 1015d303fbf..af65add8b2a 100644
--- a/src/backend/parser/gram.y
+++ b/src/backend/parser/gram.y
@@ -539,6 +539,7 @@ static Node *makeRecursiveViewSelect(char *relname, List *aliases, Node *query);
%type <list> ExclusionConstraintList ExclusionConstraintElem
%type <list> func_arg_list func_arg_list_opt
%type <node> func_arg_expr
+%type <node> on_empty
%type <list> row explicit_row implicit_row type_list array_expr_list
%type <node> case_expr case_arg when_clause case_default
%type <list> when_clause_list
@@ -16149,6 +16150,16 @@ func_application: func_name '(' ')'
n->agg_order = $7;
$$ = (Node *) n;
}
+ | func_name '(' func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $3,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $5;
+ n->agg_order = $6;
+ $$ = (Node *) n;
+ }
| func_name '(' ALL func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16162,6 +16173,16 @@ func_application: func_name '(' ')'
*/
$$ = (Node *) n;
}
+ | func_name '(' ALL func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $4,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $6;
+ n->agg_order = $7;
+ $$ = (Node *) n;
+ }
| func_name '(' DISTINCT func_arg_list opt_sort_clause ')'
{
FuncCall *n = makeFuncCall($1, $4,
@@ -16172,6 +16193,17 @@ func_application: func_name '(' ')'
n->agg_distinct = true;
$$ = (Node *) n;
}
+ | func_name '(' DISTINCT func_arg_list ',' on_empty opt_sort_clause ')'
+ {
+ FuncCall *n = makeFuncCall($1, $4,
+ COERCE_EXPLICIT_CALL,
+ @1);
+
+ n->agg_on_empty = $6;
+ n->agg_order = $7;
+ n->agg_distinct = true;
+ $$ = (Node *) n;
+ }
| func_name '(' '*' ')'
{
/*
@@ -16194,6 +16226,11 @@ func_application: func_name '(' ')'
;
+on_empty: a_expr ON EMPTY_P
+ { $$ = $1; }
+ ;
+
+
/*
* func_expr and its cousin func_expr_windowless are split out from c_expr just
* so that we have classifications for "everything that is a function call or
diff --git a/src/backend/parser/parse_func.c b/src/backend/parser/parse_func.c
index 52c4d072f0a..128d5f72a96 100644
--- a/src/backend/parser/parse_func.c
+++ b/src/backend/parser/parse_func.c
@@ -95,6 +95,7 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
bool is_column = (fn == NULL);
List *agg_order = (fn ? fn->agg_order : NIL);
Expr *agg_filter = NULL;
+ Expr *agg_on_empty = NULL;
WindowDef *over = (fn ? fn->over : NULL);
bool agg_within_group = (fn ? fn->agg_within_group : false);
bool agg_star = (fn ? fn->agg_star : false);
@@ -130,6 +131,16 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
EXPR_KIND_FILTER,
"FILTER");
+ /*
+ * Likewise transform the ON EMPTY default expression, if any. This is
+ * a minimal implementation: it is only accepted for sum() and product(),
+ * for which the standard defines it, and is implemented as a rewrite to
+ * COALESCE(call, default) below, once we know this is such a call.
+ */
+ if (fn && fn->agg_on_empty != NULL)
+ agg_on_empty = (Expr *) transformExpr(pstate, fn->agg_on_empty,
+ EXPR_KIND_FUNCTION_DEFAULT);
+
/*
* Most of the rest of the parser just assumes that functions do not have
* more than FUNC_MAX_ARGS parameters. We have to test here to protect
@@ -345,6 +356,12 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("FILTER specified, but %s is not an aggregate function",
NameListToString(funcname)),
parser_errposition(pstate, location)));
+ if (agg_on_empty != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_WRONG_OBJECT_TYPE),
+ errmsg("ON EMPTY specified, but %s is not an aggregate function",
+ NameListToString(funcname)),
+ parser_errposition(pstate, location)));
if (over)
ereport(ERROR,
(errcode(ERRCODE_WRONG_OBJECT_TYPE),
@@ -879,6 +896,51 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
transformAggregateCall(pstate, aggref, fargs, agg_order, agg_distinct);
retval = (Node *) aggref;
+
+ if (agg_on_empty != NULL)
+ {
+ char *aggname = strVal(llast(funcname));
+ CoalesceExpr *c;
+ Node *coerced;
+
+ /*
+ * Minimal ON EMPTY: only support it for the two aggregates the
+ * SQL standard actually defines it for (with a fixed identity
+ * value, per the standard, though we don't enforce the value
+ * here), and implement it as a straight rewrite to COALESCE.
+ * No new node fields, no executor changes, no interaction with
+ * DISTINCT/ALL/parallel aggregation/planagg.c to worry about.
+ */
+ if (strcmp(aggname, "sum") != 0 && strcmp(aggname, "product") != 0)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("ON EMPTY is only supported for sum() and product()"),
+ parser_errposition(pstate, location)));
+
+ coerced = coerce_to_target_type(pstate,
+ (Node *) agg_on_empty,
+ exprType((Node *) agg_on_empty),
+ aggref->aggtype,
+ -1,
+ COERCION_ASSIGNMENT,
+ COERCE_IMPLICIT_CAST,
+ -1);
+ if (coerced == NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_DATATYPE_MISMATCH),
+ errmsg("ON EMPTY expression type %s cannot be coerced to aggregate result type %s",
+ format_type_be(exprType((Node *) agg_on_empty)),
+ format_type_be(aggref->aggtype)),
+ parser_errposition(pstate, location)));
+
+ c = makeNode(CoalesceExpr);
+ c->coalescetype = aggref->aggtype;
+ /* coalescecollid will be set by parse_collate.c */
+ c->args = list_make2(aggref, coerced);
+ c->location = location;
+
+ retval = (Node *) c;
+ }
}
else
{
@@ -909,6 +971,17 @@ ParseFuncOrColumn(ParseState *pstate, List *funcname, List *fargs,
errmsg("DISTINCT is not implemented for window functions"),
parser_errposition(pstate, location)));
+ /*
+ * This minimal implementation does not support ON EMPTY for window
+ * function usage (OVER (...)); reject explicitly rather than
+ * silently ignoring the clause.
+ */
+ if (agg_on_empty != NULL)
+ ereport(ERROR,
+ (errcode(ERRCODE_FEATURE_NOT_SUPPORTED),
+ errmsg("ON EMPTY is not supported for window functions"),
+ parser_errposition(pstate, location)));
+
/*
* As above, enforce the correct argument-count limit if it's really
* an aggregate.
diff --git a/src/include/nodes/parsenodes.h b/src/include/nodes/parsenodes.h
index 910eef936f1..7fc7365e9f2 100644
--- a/src/include/nodes/parsenodes.h
+++ b/src/include/nodes/parsenodes.h
@@ -455,6 +455,7 @@ typedef struct FuncCall
List *funcname; /* qualified name of function */
List *args; /* the arguments (list of exprs) */
List *agg_order; /* ORDER BY (list of SortBy) */
+ Node *agg_on_empty; /* ON EMPTY default expression, if any */
Node *agg_filter; /* FILTER clause, if any */
struct WindowDef *over; /* OVER clause, if any */
int ignore_nulls; /* ignore nulls for window function */
diff --git a/src/test/regress/expected/aggregates.out b/src/test/regress/expected/aggregates.out
index 7d07619956f..97d65222fb8 100644
--- a/src/test/regress/expected/aggregates.out
+++ b/src/test/regress/expected/aggregates.out
@@ -3958,3 +3958,68 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+-- Minimal ON EMPTY: supported only for sum()/product(), implemented as a
+-- parse-time rewrite to COALESCE(call, default). No new executor code.
+CREATE TABLE agg_on_empty_min(a int);
+-- empty input
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+ sum
+-----
+ -1
+(1 row)
+
+INSERT INTO agg_on_empty_min VALUES (1), (2), (3), (NULL);
+-- non-empty: real result
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+ sum
+-----
+ 6
+(1 row)
+
+-- non-empty, all-NULL group: same as COALESCE, fires (documented tradeoff)
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min WHERE a IS NULL;
+ sum
+-----
+ -1
+(1 row)
+
+-- DISTINCT and ALL work with no special-casing: dedup happens upstream of
+-- the COALESCE rewrite, entirely independent of it
+SELECT sum(DISTINCT a, 0 ON EMPTY) FROM (VALUES (5), (5), (10)) v(a);
+ sum
+-----
+ 15
+(1 row)
+
+SELECT sum(ALL a, -1 ON EMPTY) FROM agg_on_empty_min WHERE a IS NULL;
+ sum
+-----
+ -1
+(1 row)
+
+-- deparsing shows the COALESCE rewrite, not the original ON EMPTY spelling
+-- (a real limitation of this minimal approach, unlike the general patch)
+CREATE VIEW agg_on_empty_min_vw AS
+ SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+SELECT pg_get_viewdef('agg_on_empty_min_vw');
+ pg_get_viewdef
+----------------------------------------------------------
+ SELECT COALESCE(sum(a), ('-1'::integer)::bigint) AS sum+
+ FROM agg_on_empty_min;
+(1 row)
+
+DROP VIEW agg_on_empty_min_vw;
+-- error cases
+SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_min; -- not sum/product
+ERROR: ON EMPTY is only supported for sum() and product()
+LINE 1: SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_min;
+ ^
+SELECT length('x', 'y' ON EMPTY); -- not an aggregate at all
+ERROR: ON EMPTY specified, but length is not an aggregate function
+LINE 1: SELECT length('x', 'y' ON EMPTY);
+ ^
+SELECT sum(a, -1 ON EMPTY) OVER () FROM agg_on_empty_min; -- not for window functions
+ERROR: ON EMPTY is not supported for window functions
+LINE 1: SELECT sum(a, -1 ON EMPTY) OVER () FROM agg_on_empty_min;
+ ^
+DROP TABLE agg_on_empty_min;
diff --git a/src/test/regress/sql/aggregates.sql b/src/test/regress/sql/aggregates.sql
index 91f8342166f..9977d293af3 100644
--- a/src/test/regress/sql/aggregates.sql
+++ b/src/test/regress/sql/aggregates.sql
@@ -1786,3 +1786,39 @@ drop table agg_hash_1;
drop table agg_hash_2;
drop table agg_hash_3;
drop table agg_hash_4;
+
+
+-- Minimal ON EMPTY: supported only for sum()/product(), implemented as a
+-- parse-time rewrite to COALESCE(call, default). No new executor code.
+
+CREATE TABLE agg_on_empty_min(a int);
+
+-- empty input
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+
+INSERT INTO agg_on_empty_min VALUES (1), (2), (3), (NULL);
+
+-- non-empty: real result
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+
+-- non-empty, all-NULL group: same as COALESCE, fires (documented tradeoff)
+SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min WHERE a IS NULL;
+
+-- DISTINCT and ALL work with no special-casing: dedup happens upstream of
+-- the COALESCE rewrite, entirely independent of it
+SELECT sum(DISTINCT a, 0 ON EMPTY) FROM (VALUES (5), (5), (10)) v(a);
+SELECT sum(ALL a, -1 ON EMPTY) FROM agg_on_empty_min WHERE a IS NULL;
+
+-- deparsing shows the COALESCE rewrite, not the original ON EMPTY spelling
+-- (a real limitation of this minimal approach, unlike the general patch)
+CREATE VIEW agg_on_empty_min_vw AS
+ SELECT sum(a, -1 ON EMPTY) FROM agg_on_empty_min;
+SELECT pg_get_viewdef('agg_on_empty_min_vw');
+DROP VIEW agg_on_empty_min_vw;
+
+-- error cases
+SELECT max(a, -1 ON EMPTY) FROM agg_on_empty_min; -- not sum/product
+SELECT length('x', 'y' ON EMPTY); -- not an aggregate at all
+SELECT sum(a, -1 ON EMPTY) OVER () FROM agg_on_empty_min; -- not for window functions
+
+DROP TABLE agg_on_empty_min;
--
2.43.0
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-28 17:36 Robert Haas <robertmhaas@gmail.com>
parent: Jeevan Chalke <jeevan.chalke@enterprisedb.com>
0 siblings, 2 replies; 14+ messages in thread
From: Robert Haas @ 2026-09-28 17:36 UTC (permalink / raw)
To: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
On Thu, Sep 24, 2026 at 9:18 AM Jeevan Chalke <
jeevan.chalke@enterprisedb.com> wrote:
> It only accepts ON EMPTY on sum() and product(), the two aggregates the
> standard actually defines this for. At parse time, once we know the
> call is sum() or product(), it is just rewritten to
> COALESCE(sum(expr), default). Nothing else changes:
>
I can't get excited about supporting this syntax for just 2 aggregates and
nothing else.
--
Robert Haas
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-28 17:40 Tom Lane <tgl@sss.pgh.pa.us>
parent: Robert Haas <robertmhaas@gmail.com>
1 sibling, 0 replies; 14+ messages in thread
From: Tom Lane @ 2026-09-28 17:40 UTC (permalink / raw)
To: Robert Haas <robertmhaas@gmail.com>; +Cc: Jeevan Chalke <jeevan.chalke@enterprisedb.com>; Vik Fearing <vik@postgresfriends.org>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
Robert Haas <robertmhaas@gmail.com> writes:
> On Thu, Sep 24, 2026 at 9:18 AM Jeevan Chalke <
> jeevan.chalke@enterprisedb.com> wrote:
>> It only accepts ON EMPTY on sum() and product(), the two aggregates the
>> standard actually defines this for. At parse time, once we know the
>> call is sum() or product(), it is just rewritten to
>> COALESCE(sum(expr), default). Nothing else changes:
> I can't get excited about supporting this syntax for just 2 aggregates and
> nothing else.
Yeah, that would be totally not in keeping with this project's usual
attitudes about extensibility.
"Rewrite at parse time" is an ugly hack anyway, because then view
dumps and so forth expose the implementation. It'd need to be
done later.
regards, tom lane
^ permalink raw reply [nested|flat] 14+ messages in thread
* Re: ON EMPTY clause for aggregate and window functions
@ 2026-09-28 17:53 Vik Fearing <vik@postgresfriends.org>
parent: Robert Haas <robertmhaas@gmail.com>
1 sibling, 0 replies; 14+ messages in thread
From: Vik Fearing @ 2026-09-28 17:53 UTC (permalink / raw)
To: Robert Haas <robertmhaas@gmail.com>; Jeevan Chalke <jeevan.chalke@enterprisedb.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; pgsql-hackers; Isaac Morland <isaac.morland@gmail.com>
On 28/09/2026 19:36, Robert Haas wrote:
> On Thu, Sep 24, 2026 at 9:18 AM Jeevan Chalke
> <jeevan.chalke@enterprisedb.com> wrote:
>
> It only accepts ON EMPTYon sum()and product(), the two aggregates the
> standard actually defines this for. At parse time, once we know the
> call is sum() or product(), it is just rewritten to
> COALESCE(sum(expr), default). Nothing else changes:
>
>
> I can't get excited about supporting this syntax for just 2 aggregates
> and nothing else.
Certainly not. Either we make it generic like we always do, or we drop
it entirely.
--
Vik Fearing
^ permalink raw reply [nested|flat] 14+ messages in thread
end of thread, other threads:[~2026-09-28 17:53 UTC | newest]
Thread overview: 14+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2026-06-26 09:11 ON EMPTY clause for aggregate and window functions Jeevan Chalke <jeevan.chalke@enterprisedb.com>
2026-06-26 13:21 ` Isaac Morland <isaac.morland@gmail.com>
2026-06-28 12:56 ` Jeevan Chalke <jeevan.chalke@enterprisedb.com>
2026-09-12 13:18 ` Jeevan Chalke <jeevan.chalke@enterprisedb.com>
2026-09-17 12:04 ` Vik Fearing <vik@postgresfriends.org>
2026-09-24 13:13 ` Jeevan Chalke <jeevan.chalke@enterprisedb.com>
2026-09-17 13:16 ` Robert Haas <robertmhaas@gmail.com>
2026-09-17 13:31 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-17 15:47 ` Vik Fearing <vik@postgresfriends.org>
2026-09-17 15:55 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-24 13:17 ` Jeevan Chalke <jeevan.chalke@enterprisedb.com>
2026-09-28 17:36 ` Robert Haas <robertmhaas@gmail.com>
2026-09-28 17:40 ` Tom Lane <tgl@sss.pgh.pa.us>
2026-09-28 17:53 ` Vik Fearing <vik@postgresfriends.org>
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox