Defines a new aggregate function.
DescriptionCREATE AGGREGATE defines a new
aggregate function. Some basic and commonly-used aggregate functions such as
count, min, max, sum,
avg and so on are already provided in Greenplum Database. If one defines
new types or needs an aggregate function not already provided, then CREATE
AGGREGATE can be used to provide the desired features.
If a schema name is given (for example, CREATE AGGREGATE myschema.myagg
...) then the aggregate function is created in the specified schema. Otherwise it
is created in the current schema.
An aggregate function is identified by its name and input data types. Two aggregate
functions in the same schema can have the same name if they operate on different input
types. The name and input data types of an aggregate function must also be distinct from the
name and input data types of every ordinary function in the same schema. This behavior is
identical to overloading of ordinary function names. See .
A simple aggregate function is made from one, two, or three ordinary functions (which must
be IMMUTABLE functions):
- a state transition function sfunc
- an optional final calculation function ffunc
- an optional combine function combinefunc
These functions are used as
follows:
sfunc( internal-state, next-data-values ) ---> next-internal-state
ffunc( internal-state ) ---> aggregate-value
combinefunc( internal-state, internal-state ) ---> next-internal-state
Greenplum Database creates a temporary variable of data type stype to
hold the current internal state of the aggregate function. At each input row, the aggregate
argument values are calculated and the state transition function is invoked with the current
state value and the new argument values to calculate a new internal state value. After all
the rows have been processed, the final function is invoked once to calculate the aggregate
return value. If there is no final function then the ending state value is returned
as-is.
You can specify combinefunc as a method for optimizing
aggregate execution. By specifying combinefunc, the
aggregate can be executed in parallel on segments first and then on the master. When a
two-level execution is performed, sfunc is executed on
the segments to generate partial aggregate results, and
combinefunc is executed on the master to aggregate
the partial results from segments. If single-level aggregation is performed, all the rows
are sent to the master and sfunc is applied to the
rows.
Single-level aggregation and two-level aggregation are equivalent execution strategies. Either
type of aggregation can be implemented in a query plan. When you implement the functions
combinefunc and sfunc, you must ensure that the
invocation of sfunc on the segment instances followed by
combinefunc on the master produce the same result as single-level
aggregation that sends all the rows to the master and then applies only the
sfunc to the rows.
An aggregate function can
provide an optional initial condition, an initial value for the internal state value. This
is specified and stored in the database as a value of type text, but it must be a valid
external representation of a constant of the state value data type. If it is not supplied
then the state value starts out NULL.
If the state transition
function is declared STRICT, then it cannot be called with
NULL inputs. With such a transition function, aggregate execution behaves
as follows. Rows with any null input values are ignored (the function is not called and the
previous state value is retained). If the initial state value is NULL, then
at the first row with all non-null input values, the first argument value replaces the state
value, and the transition function is invoked at subsequent rows with all non-null input
values. This is useful for implementing aggregates like max. Note that this
behavior is only available when state_data_type is the same as the first
input_data_type. When these types are different, you must supply a non-null initial
condition or use a nonstrict transition function.
If the state transition function is not declared STRICT, then it will be called
unconditionally at each input row, and must deal with NULL inputs and
NULL transition values for itself. This allows the aggregate author to
have full control over the aggregate's handling of NULL values.
If the final function is declared
STRICT, then it will not be called when the ending state value is
NULL; instead a NULL result will be returned
automatically. (This is the normal behavior of STRICT functions.) In any
case the final function has the option of returning a NULL value. For
example, the final function for avg returns NULL when it
sees there were zero input rows.
Sometimes it is useful to declare the final function as taking not just
the state value, but extra parameters corresponding to the aggregate's
input values. The main reason for doing this is if the final function
is polymorphic and the state value's data type would be inadequate to
pin down the result type. These extra parameters are always passed as
NULL (and so the final function must not be strict when
the FINALFUNC_EXTRA option is used), but nonetheless they
are valid parameters. The final function could for example make use
of get_fn_expr_argtype to identify the actual argument type
in the current call.
An aggregate can optionally support moving-aggregate mode, as described in Moving-Aggregate Mode in the PostgreSQL
documentation. This requires specifying the msfunc,
minfunc, and
mstype functions, and optionally the
mspace,
mfinalfunc,
mfinalfunc_extra, and
minitcond functions. Except for
minvfunc, these functions work like the
corresponding simple-aggregate functions without m; they
define a separate implementation of the aggregate that includes an inverse transition
function.
The syntax with ORDER BY in the parameter list creates a special type of
aggregate called an ordered-set aggregate; or if HYPOTHETICAL is
specified, then a hypothetical-set aggregate is created. These aggregates operate
over groups of sorted values in order-dependent ways, so that specification of an input sort
order is an essential part of a call. Also, they can have direct arguments, which are
arguments that are evaluated only once per aggregation rather than once per input row.
Hypothetical-set aggregates are a subclass of ordered-set aggregates in which some of the
direct arguments are required to match, in number and data types, the aggregated argument
columns. This allows the values of those direct arguments to be added to the collection of
aggregate-input rows as an additional "hypothetical" row.
Single argument aggregate functions, such as min or
max, can sometimes be optimized by looking into an index instead of scanning every input
row. If this aggregate can be so optimized, indicate it by specifying a sort operator. The
basic requirement is that the aggregate must yield the first element in the sort ordering
induced by the operator; in other
words:
SELECT agg(col) FROM tab;
must be equivalent to:
SELECT col FROM tab ORDER BY col USING sortop LIMIT 1;Further
assumptions are that the aggregate function ignores NULL inputs, and that
it delivers a NULL result if and only if there were no non-null inputs.
Ordinarily, a data type's < operator is the proper sort operator for
MIN, and > is the proper sort operator for
MAX. Note that the optimization will never actually take effect unless
the specified operator is the "less than" or "greater than" strategy member of a B-tree
index operator class.
To be able to create an aggregate function, you must have USAGE privilege
on the argument types, the state type, and the return type, as well as
EXECUTE privilege on the transition and final functions.
Notes
The ordinary functions used to define a new aggregate function must
be defined first. Note that in this release of Greenplum Database, it
is required that the sfunc, ffunc, and combinefunc functions
used to create the aggregate are defined as IMMUTABLE.
If the value of the Greenplum Database server configuration parameter
gp_enable_multiphase_agg is off, only
single-level aggregation is performed.
Any compiled code (shared library files) for custom functions must
be placed in the same location on every host in your Greenplum Database
array (master and all segments). This location must also be in the LD_LIBRARY_PATH
so that the server can locate the files.
In previous versions of Greenplum Database, there was a concept of
ordered aggregates. Since version 6, any aggregate can be called as an
ordered aggregate, using the syntax:
name ( arg [ , ... ] [ORDER BY sortspec [ , ...]] )
The ORDERED keyword is accepted for backwards compatibility, but
is ignored.
In previous versions of Greenplum Database, the COMBINEFUNC option was called
PREFUNC. It is still accepted for backwards compatibility, as a synonym for
COMBINEFUNC.