CREATE_AGGREGATE(7pg14)
okay so this is CREATE AGGREGATE, straight out of the PostgreSQL 14.24 docs, section 7 β the glow-up guide to teaching the database a brand new party trick π
πΈ NAME πΈ
CREATE_AGGREGATE β define a new aggregate function β¨
β¨ SYNOPSIS β¨
okay bestie, there are three whole ways to write this and you're gonna meet all of them. no skipping π
CREATE [ OR REPLACE ] AGGREGATE name ( [ argmode ] [ argname ] arg_data_type [ , ... ] ) (
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , COMBINEFUNC = combinefunc ]
[ , SERIALFUNC = serialfunc ]
[ , DESERIALFUNC = deserialfunc ]
[ , INITCOND = initial_condition ]
[ , MSFUNC = msfunc ]
[ , MINVFUNC = minvfunc ]
[ , MSTYPE = mstate_data_type ]
[ , MSSPACE = mstate_data_size ]
[ , MFINALFUNC = mffunc ]
[ , MFINALFUNC_EXTRA ]
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = minitial_condition ]
[ , SORTOP = sort_operator ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
)
second one, the ordered-set era β note the ORDER BY in the parameter list, it's the whole point π₯
CREATE [ OR REPLACE ] AGGREGATE name ( [ [ argmode ] [ argname ] arg_data_type [ , ... ] ]
ORDER BY [ argmode ] [ argname ] arg_data_type [ , ... ] ) (
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , INITCOND = initial_condition ]
[ , PARALLEL = { SAFE | RESTRICTED | UNSAFE } ]
[ , HYPOTHETICAL ]
)
or the old syntax π«Ά (yes it still exists, it's giving vintage, we respect it)
CREATE [ OR REPLACE ] AGGREGATE name (
BASETYPE = base_type,
SFUNC = sfunc,
STYPE = state_data_type
[ , SSPACE = state_data_size ]
[ , FINALFUNC = ffunc ]
[ , FINALFUNC_EXTRA ]
[ , FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , COMBINEFUNC = combinefunc ]
[ , SERIALFUNC = serialfunc ]
[ , DESERIALFUNC = deserialfunc ]
[ , INITCOND = initial_condition ]
[ , MSFUNC = msfunc ]
[ , MINVFUNC = minvfunc ]
[ , MSTYPE = mstate_data_type ]
[ , MSSPACE = mstate_data_size ]
[ , MFINALFUNC = mffunc ]
[ , MFINALFUNC_EXTRA ]
[ , MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } ]
[ , MINITCOND = minitial_condition ]
[ , SORTOP = sort_operator ]
)
π DESCRIPTION π
so CREATE AGGREGATE defines a new aggregate function, periodt. and CREATE OR REPLACE AGGREGATE will either define a brand new one or replace a definition that already exists π
some basic and commonly-used aggregate functions ship with the distribution already β they're documented in Section 9.21, go look π. but if you're defining new types, or you need an aggregate function that isn't already provided, then CREATE AGGREGATE is literally the tool for the job β¨
π¦ replacing an existing one
when you're replacing an existing definition, the argument types, the result type, and the number of direct arguments may not be changed. also the new definition has to be the same kind as the old one β ordinary aggregate, ordered-set aggregate, or hypothetical-set aggregate, no switching mid-glow-up π
π which schema tho
if a schema name is given (like, for example, CREATE AGGREGATE myschema.myagg ...) then the aggregate function gets created in that specified schema. otherwise it's created in the current schema. simple as πΈ
π how it's identified
an aggregate function is identified by its name and its input data type(s). two aggregates in the same schema can totally have the same name if they operate on different input types π― and the name plus input data type(s) of an aggregate must also be distinct from the name and input data type(s) of every ordinary function in the same schema. this behavior is identical to overloading of ordinary function names (see CREATE FUNCTION (CREATE_FUNCTION(7))) β same vibe, different table π«Ά
β the actual mechanics (the good part)
a simple aggregate function is made from one or two ordinary functions: a state transition function sfunc, and an optional final calculation function ffunc. they're used like this:
sfunc( internal-state, next-data-values ) ---> next-internal-state
ffunc( internal-state ) ---> aggregate-value
PostgreSQL creates a temporary variable of data type stype to hold the current internal state of the aggregate. at each input row, the aggregate argument value(s) are calculated and the state transition function is invoked with the current state value and the new argument value(s) to calculate a new internal state value. after all the rows have been processed, the final function is invoked once to calculate the aggregate's return value π― and if there is no final function, then the ending state value is returned as-is. no extra steps, no drama.
π initial condition
an aggregate function can provide an initial condition β that is, 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's not supplied, then the state value starts out null. that's it that's the rule.
π§ strict vs not-strict sfunc
if the state transition function is declared "strict", then it cannot be called with null inputs. with such a transition function, aggregate execution behaves like this:
- 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-nonnull input values, the first argument value replaces the state value, and the transition function is invoked at each subsequent row with all-nonnull input values β¨
this is super handy for implementing aggregates like max. note that this behavior is only available when state_data_type is the same as the first arg_data_type. when these types are different, you must supply a nonnull initial condition or use a nonstrict transition function β no cap π§’
if the state transition function is not strict, then it will be called unconditionally at each input row, and it must deal with null inputs and null state values for itself. this lets the aggregate author have full control over the aggregate's handling of null values πͺ
π final function strictness
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. (of course, this is just the normal behavior of strict functions, nothing new here π) 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. iconic behavior honestly.
π FINALFUNC_EXTRA and why it's a vibe
sometimes it's 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. iykyk π
π₯ moving-aggregate mode
an aggregate can optionally support moving-aggregate mode, as described in Section 38.12.1. this requires specifying the MSFUNC, MINVFUNC, and MSTYPE parameters, and optionally the MSSPACE, MFINALFUNC, MFINALFUNC_EXTRA, MFINALFUNC_MODIFY, and MINITCOND parameters πββοΈπ¨
except for MINVFUNC, these parameters work like the corresponding simple-aggregate parameters without the M β they define a separate implementation of the aggregate that includes an inverse transition function. yes, separate implementation. she's got layers.
πΈ ordered-set and hypothetical-set aggregates
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 specification of an input sort order is an essential part of a call β not optional, not decorative, essential π
also, they can have direct arguments, which are arguments that are evaluated only once per aggregation rather than once per input row. so much chiller than the row-by-row life.
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 π¦ yes, that's where the name comes from, you're welcome.
π§ partial aggregation & COMBINEFUNC
an aggregate can optionally support partial aggregation, as described in Section 38.12.4. this requires specifying the COMBINEFUNC parameter π€
if the state_data_type is internal, it's usually also appropriate to provide the SERIALFUNC and DESERIALFUNC parameters so that parallel aggregation is possible. note that the aggregate must also be marked PARALLEL SAFE to enable parallel aggregation β don't forget the vibe check on that one or it just won't happen π«
π the MIN/MAX index trick
aggregates that behave like 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, SORTOP π
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 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 π
careful bestie π β 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. like, it'll just sit there looking cute and doing nothing.
π privileges (yes, you need them)
to be able to create an aggregate function, you must have USAGE privilege on the argument types, the state type(s), and the return type β as well as EXECUTE privilege on the supporting functions π
that's the whole permission situation. no shortcuts, no borrowing your friend's login. π«Ά
π¦ PARAMETERS π¦
okay bestie, this is the whole parameter menu for CREATE AGGREGATE β every knob, default, and vibe check. no cap, you're gonna need all of these. π
nameβ the name of the aggregate function to create, optionally schema-qualified. slay πargmodeβ the mode of an argument:INorVARIADIC. quick PSA: aggregate functions do not supportOUTarguments. if omitted, the default isIN. only the last argument can be markedVARIADIC. π«Άargnameβ the name of an argument. this is currently only useful for documentation purposes. if omitted, the argument has no name. iykyk β¨arg_data_typeβ an input data type on which this aggregate function operates. to create a zero-argument aggregate function, write*in place of the list of argument specifications. (an example of such an aggregate iscount(*).) iconic πΈbase_typeβ in the old syntax forCREATE AGGREGATE, the input data type is specified by abasetypeparameter rather than being written next to the aggregate name. note that this syntax allows only one input parameter. to define a zero-argument aggregate function with this syntax, specify thebasetypeas"ANY"(not*). ordered-set aggregates cannot be defined with the old syntax. it's giving legacy but valid π§sfuncβ the name of the state transition function to be called for each input row. for a normal N-argument aggregate function, thesfuncmust take N+1 arguments, the first being of typestate_data_typeand the rest matching the declared input data type(s) of the aggregate. the function must return a value of typestate_data_type. this function takes the current state value and the current input data value(s), and returns the next state value. for ordered-set (including hypothetical-set) aggregates, the state transition function receives only the current state value and the aggregated arguments, not the direct arguments. otherwise it is the same. main character energy πstate_data_typeβ the data type for the aggregate's state value. periodt πstate_data_sizeβ the approximate average size (in bytes) of the aggregate's state value. if this parameter is omitted or is zero, a default estimate is used based on thestate_data_type. the planner uses this value to estimate the memory required for a grouped aggregate query. planner math, bestie β¨ffuncβ the name of the final function called to compute the aggregate's result after all input rows have been traversed. for a normal aggregate, this function must take a single argument of typestate_data_type. the return data type of the aggregate is defined as the return type of this function. ifffuncis not specified, then the ending state value is used as the aggregate's result, and the return type isstate_data_type. for ordered-set (including hypothetical-set) aggregates, the final function receives not only the final state value, but also the values of all the direct arguments. ifFINALFUNC_EXTRAis specified, then in addition to the final state value and any direct arguments, the final function receives extra NULL values corresponding to the aggregate's regular (aggregated) arguments. this is mainly useful to allow correct resolution of the aggregate result type when a polymorphic aggregate is being defined. obsessed with the extra NULLs πFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE }β this option specifies whether the final function is a pure function that does not modify its arguments.READ_ONLYindicates it does not; the other two values indicate that it may change the transition state value. see Notes below for more detail. the default isREAD_ONLY, except for ordered-set aggregates, for which the default isREAD_WRITE. vibe check on side effects π¦combinefuncβ thecombinefuncfunction may optionally be specified to allow the aggregate function to support partial aggregation. if provided, thecombinefuncmust combine twostate_data_typevalues, each containing the result of aggregation over some subset of the input values, to produce a newstate_data_typethat represents the result of aggregating over both sets of inputs. this function can be thought of as ansfunc, where instead of acting upon an individual input row and adding it to the running aggregate state, it adds another aggregate state to the running state. thecombinefuncmust be declared as taking two arguments of thestate_data_typeand returning a value of thestate_data_type. optionally this function may be βstrictβ. in this case the function will not be called when either of the input states are null; the other state will be taken as the correct result. for aggregate functions whosestate_data_typeisinternal, thecombinefuncmust not be strict. in this case thecombinefuncmust ensure that null states are handled correctly and that the state being returned is properly stored in the aggregate memory context. π¨ internal-state girlies, pay attention πserialfuncβ an aggregate function whosestate_data_typeisinternalcan participate in parallel aggregation only if it has aserialfuncfunction, which must serialize the aggregate state into abyteavalue for transmission to another process. this function must take a single argument of typeinternaland return typebytea. a correspondingdeserialfuncis also required. parallel slay π₯deserialfuncβ deserialize a previously serialized aggregate state back intostate_data_type. this function must take two arguments of typesbyteaandinternal, and produce a result of typeinternal. (note: the second,internalargument is unused, but is required for type safety reasons.) typing rules are rules πinitial_conditionβ the initial setting for the state value. this must be a string constant in the form accepted for the data typestate_data_type. if not specified, the state value starts out null. starting fresh π±msfuncβ the name of the forward state transition function to be called for each input row in moving-aggregate mode. this is exactly like the regular transition function, except that its first argument and result are of typemstate_data_type, which might be different fromstate_data_type. moving-aggregate mode activated β¨minvfuncβ the name of the inverse state transition function to be used in moving-aggregate mode. this function has the same argument and result types asmsfunc, but it is used to remove a value from the current aggregate state, rather than add a value to it. the inverse transition function must have the same strictness attribute as the forward state transition function. subtract era πmstate_data_typeβ the data type for the aggregate's state value, when using moving-aggregate mode. moving state, moving vibes π¦mstate_data_sizeβ the approximate average size (in bytes) of the aggregate's state value, when using moving-aggregate mode. this works the same asstate_data_size. same math, moving mode βmffuncβ the name of the final function called to compute the aggregate's result after all input rows have been traversed, when using moving-aggregate mode. this works the same asffunc, except that its first argument's type ismstate_data_typeand extra dummy arguments are specified by writingMFINALFUNC_EXTRA. the aggregate result type determined bymffuncormstate_data_typemust match that determined by the aggregate's regular implementation. matching sets, no cap πMFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE }β this option is likeFINALFUNC_MODIFY, but it describes the behavior of the moving-aggregate final function. same energy, moving edition πminitial_conditionβ the initial setting for the state value, when using moving-aggregate mode. this works the same asinitial_condition. fresh start, moving mode π±sort_operatorβ the associated sort operator for a MIN- or MAX-like aggregate. this is just an operator name (possibly schema-qualified). the operator is assumed to have the same input data types as the aggregate (which must be a single-argument normal aggregate). MIN/MAX besties only πPARALLEL = { SAFE | RESTRICTED | UNSAFE }β the meanings ofPARALLEL SAFE,PARALLEL RESTRICTED, andPARALLEL UNSAFEare the same as inCREATE FUNCTION. an aggregate will not be considered for parallelization if it is markedPARALLEL UNSAFE(which is the default!) orPARALLEL RESTRICTED. note that the parallel-safety markings of the aggregate's support functions are not consulted by the planner, only the marking of the aggregate itself. π¨ default is UNSAFE, bestie β don't forget πHYPOTHETICALβ for ordered-set aggregates only, this flag specifies that the aggregate arguments are to be processed according to the requirements for hypothetical-set aggregates: that is, the last few direct arguments must match the data types of the aggregated (WITHIN GROUP) arguments. theHYPOTHETICALflag has no effect on run-time behavior, only on parse-time resolution of the data types and collations of the aggregate's arguments. parse-time drama only π
and bestie, the parameters of CREATE AGGREGATE can be written in any order, not just the order illustrated above. mix and match, you got this β¨
π¦ NOTES (the tea β) π¦
In parameters that specify support function names, you can write a schema name if needed, for example SFUNC = public.sum. Do not write argument types there, however β the argument types of the support functions are determined from other parameters. ok so like, the function already knows its own vibe, don't @ it with types π
Ordinarily, PostgreSQL functions are expected to be true functions that do not modify their input values. However, an aggregate transition function, when used in the context of an aggregate, is allowed to cheat and modify its transition-state argument in place. no cap, it's literally allowed to be messy π This can provide substantial performance benefits compared to making a fresh copy of the transition state each time. girl math: zero copies = zero problems π₯
Likewise, while an aggregate final function is normally expected not to modify its input values, sometimes it is impractical to avoid modifying the transition-state argument. Such behavior must be declared using the FINALFUNC_MODIFY parameter. The READ_WRITE value indicates that the final function modifies the transition state in unspecified ways. This value prevents use of the aggregate as a window function, and it also prevents merging of transition states for aggregate calls that share the same input values and transition functions. The SHAREABLE value indicates that the transition function cannot be applied after the final function, but multiple final-function calls can be performed on the ending transition state value. This value prevents use of the aggregate as a window function, but it allows merging of transition states. (That is, the optimization of interest here is not applying the same final function repeatedly, but applying different final functions to the same ending transition state value. This is allowed as long as none of the final functions are marked READ_WRITE.) π«Ά
π lowkey important: once you've run a final function over a state, the state's done. don't be out here trying to continue the aggregation afterwards unless the rules above say it's chill.
β¨ moving-aggregate mode (the main character era) β¨
If an aggregate supports moving-aggregate mode, it will improve calculation efficiency when the aggregate is used as a window function for a window with moving frame start (that is, a frame start mode other than UNBOUNDED PRECEDING). Conceptually, the forward transition function adds input values to the aggregate's state when they enter the window frame from the bottom, and the inverse transition function removes them again when they leave the frame at the top. So, when values are removed, they are always removed in the same order they were added. Whenever the inverse transition function is invoked, it will thus receive the earliest added but not yet removed argument value(s). The inverse transition function can assume that at least one row will remain in the current state after it removes the oldest row. (When this would not be the case, the window function mechanism simply starts a fresh aggregation, rather than using the inverse transition function.) it's giving queue energy, fr fr π
The forward transition function for moving-aggregate mode is not allowed to return NULL as the new state value. If the inverse transition function returns NULL, this is taken as an indication that the inverse function cannot reverse the state calculation for this particular input, and so the aggregate calculation will be redone from scratch for the current frame starting position. This convention allows moving-aggregate mode to be used in situations where there are some infrequent cases that are impractical to reverse out of the running state value. like, if the math won't undo, just say so and we'll restart β iconic honesty π
If no moving-aggregate implementation is supplied, the aggregate can still be used with moving frames, but PostgreSQL will recompute the whole aggregation whenever the start of the frame moves. Note that whether or not the aggregate supports moving-aggregate mode, PostgreSQL can handle a moving frame end without recalculation; this is done by continuing to add new values to the aggregate's state. This is why use of an aggregate as a window function requires that the final function be read-only: it must not damage the aggregate's state value, so that the aggregation can be continued even after an aggregate result value has been obtained for one set of frame boundaries. bestie do not scribble on the state, we're literally still using it πβ
πΈ ordered-set aggregate tea πΈ
The syntax for ordered-set aggregates allows VARIADIC to be specified for both the last direct parameter and the last aggregated (WITHIN GROUP) parameter. However, the current implementation restricts use of VARIADIC in two ways:
- ordered-set aggregates can only use
VARIADIC "any", not other variadic array types. - if the last direct parameter is
VARIADIC "any", then there can be only one aggregated parameter and it must also beVARIADIC "any".
(In the representation used in the system catalogs, these two parameters are merged into a single VARIADIC "any" item, since pg_proc cannot represent functions with more than one VARIADIC parameter.) check the receipts, they literally fuse together in there π³ If the aggregate is a hypothetical-set aggregate, the direct arguments that match the VARIADIC "any" parameter are the hypothetical ones; any preceding parameters represent additional direct arguments that are not constrained to match the aggregated arguments.
Currently, ordered-set aggregates do not need to support moving-aggregate mode, since they cannot be used as window functions. not invited to the window party, no drama π
Partial (including parallel) aggregation is currently not supported for ordered-set aggregates. Also, it will never be used for aggregate calls that include DISTINCT or ORDER BY clauses, since those semantics cannot be supported during partial aggregation. ngl this one's a hard no, the semantics just don't survive being split up π€
π§ EXAMPLES π§
See Section 38.12. yeah girl, the actual example era lives over there β go peek, it's worth it β
π COMPATIBILITY π
CREATE AGGREGATE is a PostgreSQL language extension. The SQL standard does not provide for user-defined aggregate functions. so like, we invented this one, the SQL standard could never πβ¨
π SEE ALSO π
ALTER AGGREGATE(ALTER_AGGREGATE(7)) β when you gotta tweak the vibes after the factDROP AGGREGATE(DROP_AGGREGATE(7)) β when it's time to say bye bestie π¦
okay that's the whole page, you ate that π
this was PostgreSQL 14.24, dated 2026, and it's the CREATE AGGREGATE(7) page β go forth and aggregate, queen πβ¨
π¦ where this page comes from
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql14 14.24-160000.1.1 Β· PostgreSQL
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms