CREATE_AGGREGATE(7pg18)

๐Ÿ“ฆ version 18.6, in opensuse-leap 16.0

๐Ÿ’… CREATE_AGGREGATE ๐Ÿ’…

okay so this is CREATE AGGREGATE(7) from the PostgreSQL 18.6 Documentation, and bestie, it's a whole saga, so buckle up ๐ŸŽ€ (it's long enough that it comes in parts, and this is part one โ€” no sign-off, we're just getting started โœจ)


โœจ NAME โœจ

CREATE_AGGREGATE โ€” define a new aggregate function. that's it, that's the job, and it's iconic ๐Ÿ‘‘


๐ŸŒธ SYNOPSIS ๐ŸŒธ

okay so there are three ways to say this, and the first one is the main character:

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 } ]
)

and then there's the ordered-set / hypothetical-set variant, which is giving very much "sort first, ask questions later":

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, aka the vintage fit that still slays:

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 brand new aggregate function. and CREATE OR REPLACE AGGREGATE is the glow-up version โ€” it'll either define a fresh one or replace an existing definition. some basic, commonly-used aggregate functions already ship with the distribution (they're documented over in Section 9.21, go look ๐Ÿ‘€). but if you're out here defining new types, or you need an aggregate function that nobody already provided, then CREATE AGGREGATE is your girl, and she can give you exactly the features you want ๐Ÿ’…

when you're replacing an existing definition, listen up: the argument types, result type, and 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 lanes mid-replacement, that's not the vibe ๐Ÿ™…โ€โ™€๏ธ

if you give a schema name (like, for example, CREATE AGGREGATE myschema.myagg ...) then the aggregate function gets created in that schema. otherwise it's created in the current schema. simple as ๐Ÿซถ

an aggregate function is identified by its name and input data type(s). two aggregates in the same schema can totally share a name as long as they operate on different input types. and the name + input data type(s) of an aggregate also has to be distinct from the name + input data type(s) of every ordinary function in that same schema. this behavior is identical to overloading of ordinary function names (peep CREATE FUNCTION (CREATE_FUNCTION(7))) โ€” so it's not new, it's just the rules, periodt.


๐ŸŒˆ the simple aggregate pipeline

a simple aggregate function is made from one or two ordinary functions: a state transition function sfunc, and an optional final calculation function ffunc. here's how they get used:

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) get calculated and the state transition function is invoked with the current state value plus the new argument value(s), to calculate a new internal state value. after all the rows have been processed, the final function gets invoked once to calculate the aggregate's return value. and if there's no final function? the ending state value is just returned as-is. no notes โœจ


๐Ÿ“ initial conditions & the strictness lore

an aggregate function can provide an initial condition โ€” that's an initial value for the internal state value. it's specified and stored in the database as a value of type text, but ngl 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.

now, the strict stuff, and this part is important so pay attention bestie:

if the state transition function is declared โ€œstrictโ€, then it cannot be called with null inputs. with a transition function like that, 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. but note: this behavior is only available when state_data_type is the same as the first arg_data_type. when those types are different, you must supply a nonnull initial condition or use a nonstrict transition function. those are the options, i don't make the rules ๐Ÿ’โ€โ™€๏ธ

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 all by itself. this gives the aggregate author full control over how the aggregate handles null values. main character energy, honestly ๐Ÿ‘‘

if the final function is declared โ€œstrictโ€, then it won't be called when the ending state value is null โ€” instead a null result gets returned automatically. (obviously, that's just normal behavior for strict functions, we knew that ๐Ÿ™ˆ) 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.


๐Ÿงš FINALFUNC_EXTRA and the extra-params thing

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 you'd do 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. cute, right? ๐ŸŽ€


๐Ÿ’œ moving-aggregate mode

an aggregate can optionally support moving-aggregate mode, as described in Section 36.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 exactly like the corresponding simple-aggregate parameters without the M โ€” they define a separate implementation of the aggregate that includes an inverse transition function. two implementations, one aggregate, we love a versatile queen ๐Ÿ’…


๐Ÿ‘‘ ordered-set & 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 gets created. these aggregates operate over groups of sorted values in order-dependent ways, so specifying 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. huge W.

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 lets the values of those direct arguments be added to the collection of aggregate-input rows as an additional โ€œhypotheticalโ€ row. yeah. that's the whole point of them โœจ


๐Ÿ”ฅ partial aggregation & parallel vibes

an aggregate can optionally support partial aggregation, as described in Section 36.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. all the pieces have to align, no skipping steps ๐Ÿซถ


โญ the MIN/MAX index optimization (iykyk)

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. 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. 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. so like, specify it right or it does nothing, bestie ๐Ÿ’€


๐ŸŽ€ privileges check

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. no privileges, no aggregate. that's the whole vibe check ๐ŸŒธ


๐Ÿ’– PARAMETERS ๐Ÿ’–

okay so this is the part where we meet the whole cast of characters ๐ŸŽญ every single one of these is a thing you can hand to CREATE AGGREGATE, and they all get to sit wherever they want (more on that at the bottom). let's go one by one, no skimming, we're doing this properly ๐Ÿ’…


name

the name of the aggregate function you're creating โ€” optionally schema-qualified, so you can be like myschema.myagg if you're feeling fancy โœจ

argmode

the mode of an argument. your options are IN or VARIADIC. quick heads up: aggregate functions do not support OUT arguments, so don't even try it ๐Ÿ™ˆ if you just leave it out, the default is IN. and psst โ€” only the last argument can be marked VARIADIC.

argname

the name of an argument. lowkey rn this is only useful for documentation purposes ๐Ÿ“ so it's purely for the ~aesthetic~ and for people reading your code later. if you omit it, the argument just has no name.

arg_data_type

an input data type that this aggregate function operates on. and here's a cute trick: to make a zero-argument aggregate function, you write * in place of the whole list of argument specifications. the iconic example of this is count(*) ๐Ÿ‘‘

base_type

this one's for the old syntax of CREATE AGGREGATE, where the input data type gets specified by a basetype parameter instead of being written right next to the aggregate name. โš ๏ธ important: this syntax only allows one input parameter. and if you want a zero-argument aggregate function with this old syntax, you specify the basetype as "ANY" โ€” not *. also, ordered-set aggregates cannot be defined with the old syntax, periodt.

sfunc

the name of the state transition function that gets called for every single input row ๐Ÿ”

for a normal N-argument aggregate function, sfunc has to take N+1 arguments: the first one is of type state_data_type, and the rest match the declared input data type(s) of the aggregate. it must return a value of type state_data_type. basically it takes the current state value plus the current input data value(s), and hands you back the next state value. chef's kiss ๐Ÿซถ

for ordered-set aggregates (including hypothetical-set ones), the state transition function receives only the current state value and the aggregated arguments โ€” not the direct arguments. other than that, it's exactly the same.

state_data_type

the data type for the aggregate's state value. that's it, that's the whole vibe ๐ŸŽ€

state_data_size

the approximate average size (in bytes) of the aggregate's state value. if you skip this or set it to zero, a default estimate gets used based on state_data_type. the planner uses this number to estimate how much memory a grouped aggregate query is gonna need ๐Ÿง  so it's giving "helpful hint for the planner" energy.

ffunc

the name of the final function called to compute the aggregate's result after all the input rows have been traversed ๐Ÿ

for a normal aggregate, this function takes a single argument of type state_data_type. and the aggregate's return data type is defined as the return type of this function. if you don't specify ffunc, then the ending state value is used as the aggregate's result, and the return type is state_data_type. easy โœจ

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.

and if FINALFUNC_EXTRA is specified, then on top of the final state value and any direct arguments, the final function also 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 โ€” iykyk ๐Ÿ’…

FINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE }

this option says whether the final function is a pure function that does not modify its arguments. READ_ONLY means it doesn't touch them; the other two values mean it may change the transition state value. see Notes below for more detail. the default is READ_ONLY โ€” except for ordered-set aggregates, where the default is READ_WRITE. โš ๏ธ

combinefunc

combinefunc is optional, and if you give it, it lets the aggregate function support partial aggregation ๐Ÿ”ฅ

if provided, combinefunc must combine two state_data_type values โ€” each one holding the result of aggregation over some subset of the input values โ€” to produce a new state_data_type that represents the result of aggregating over both sets of inputs. think of it as an sfunc, except instead of acting on an individual input row and adding it to the running aggregate state, it adds another aggregate state to the running state. inception but make it math ๐ŸŒ€

combinefunc must be declared as taking two arguments of the state_data_type and returning a value of the state_data_type. optionally, this function may be โ€œstrictโ€. in that case the function won't be called when either of the input states are null โ€” the other state just gets taken as the correct result.

for aggregate functions whose state_data_type is internal, the combinefunc must not be strict. in that case combinefunc must make sure that null states are handled correctly and that the state being returned is properly stored in the aggregate memory context. no pressure bestie ๐Ÿซ 

serialfunc

an aggregate function whose state_data_type is internal can only participate in parallel aggregation if it has a serialfunc. this function must serialize the aggregate state into a bytea value so it can be transmitted to another process ๐Ÿ“ฆ

it must take a single argument of type internal and return type bytea. and heads up โ€” a corresponding deserialfunc is also required, they're a package deal ๐ŸŽ

deserialfunc

deserialize a previously serialized aggregate state back into state_data_type. this function must take two arguments of types bytea and internal, and produce a result of type internal.

(quick note: the second, internal argument is unused, but it's required for type safety reasons. it's just there for the vibes. ๐Ÿ™ˆ)

initial_condition

the initial setting for the state value. this must be a string constant in the form accepted for the data type state_data_type. if you don't specify it, the state value starts out as null โœจ

msfunc

the name of the forward state transition function to be called for each input row in moving-aggregate mode. it's exactly like the regular transition function, except its first argument and its result are of type mstate_data_type, which might be different from state_data_type ๐Ÿ‘€

minvfunc

the name of the inverse state transition function used in moving-aggregate mode. same argument and result types as msfunc, but it's used to remove a value from the current aggregate state instead of adding one โž–

the inverse transition function must have the same strictness attribute as the forward state transition function. they have to match, it's a whole thing ๐Ÿ’…

mstate_data_type

the data type for the aggregate's state value when you're using moving-aggregate mode.

mstate_data_size

the approximate average size (in bytes) of the aggregate's state value when you're using moving-aggregate mode. works the exact same way as state_data_size.

mffunc

the name of the final function called to compute the aggregate's result after all input rows have been traversed, when you're using moving-aggregate mode. works the same as ffunc, except its first argument's type is mstate_data_type, and extra dummy arguments get specified by writing MFINALFUNC_EXTRA.

and important: the aggregate result type determined by mffunc or mstate_data_type must match the one determined by the aggregate's regular implementation. no mismatches allowed ๐Ÿ”’

MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE }

this one's just like FINALFUNC_MODIFY, but it describes the behavior of the moving-aggregate final function instead.

minitial_condition

the initial setting for the state value, when using moving-aggregate mode. works the same as initial_condition ๐ŸŒธ

sort_operator

the associated sort operator for a MIN- or MAX-like aggregate. it's just an operator name, possibly schema-qualified. the operator is assumed to have the same input data types as the aggregate โ€” and that aggregate must be a single-argument normal aggregate, fyi ๐Ÿ“Œ

PARALLEL = { SAFE | RESTRICTED | UNSAFE }

the meanings of PARALLEL SAFE, PARALLEL RESTRICTED, and PARALLEL UNSAFE are the same as in CREATE FUNCTION. an aggregate will not be considered for parallelization if it's marked PARALLEL UNSAFE (which, btw, is the default!) or PARALLEL RESTRICTED.

๐Ÿšจ also important: the planner does not consult the parallel-safety markings of the aggregate's support functions โ€” only the marking of the aggregate itself. so don't rely on your helper functions to save you.

HYPOTHETICAL

for ordered-set aggregates only, this flag says that the aggregate arguments are to be processed according to the requirements for hypothetical-set aggregates: meaning the last few direct arguments must match the data types of the aggregated (WITHIN GROUP) arguments.

and here's the tea โ˜• the HYPOTHETICAL flag has no effect on run-time behavior โ€” only on parse-time resolution of the data types and collations of the aggregate's arguments. it's all about how things get figured out up front, not how they run.


๐Ÿ’ก and the final little freedom moment: the parameters of CREATE AGGREGATE can be written in any order, not just the order illustrated above. go wild, bestie, arrange them however your heart desires ๐ŸŒˆ

โœจ NOTES โœจ

Okay bestie, notes time. These are the little lore drops that make the whole aggregate thing make sense, and honestly? iconic.

So when you're writing parameters that name support functions, you can put a schema name in there if you need one โ€” like SFUNC = public.sum. But do not write argument types in there. Nope. The argument types of the support functions are figured out from the other parameters. That's the rule. ๐Ÿ’…

Normally, PostgreSQL functions are supposed to be true functions, meaning they don't modify their input values. But an aggregate transition function, when it's used in the context of an aggregate, is allowed to cheat and modify its transition-state argument in place. And that's actually a huge performance slay compared to making a fresh copy of the transition state every single time. โœจ

Same energy with the final function: an aggregate final function is normally expected not to modify its input values, but sometimes it's just impractical to avoid modifying the transition-state argument. If that's the case, you must declare it with the FINALFUNC_MODIFY parameter.

  • The READ_WRITE value means the final function modifies the transition state in unspecified ways. This prevents using the aggregate as a window function, and it also prevents merging transition states for aggregate calls that share the same input values and transition functions. ๐Ÿ’€
  • The SHAREABLE value means 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 prevents using the aggregate as a window function, but it allows merging of transition states.

And the parenthetical tea: 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. ๐Ÿซถ

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.) ๐Ÿฆ‹

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, that's taken as an indication that the inverse function cannot reverse the state calculation for this particular input, 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. ๐Ÿ˜ญ

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. And note: whether or not the aggregate supports moving-aggregate mode, PostgreSQL can handle a moving frame end without recalculation. It does this by continuing to add new values to the aggregate's state. That is why using an aggregate as a window function requires the final function to be read-only: it must not damage the aggregate's state value, so the aggregation can be continued even after an aggregate result value has been obtained for one set of frame boundaries. ๐Ÿ”ฅ

The syntax for ordered-set aggregates allows VARIADIC to be specified for both the last direct parameter and the last aggregated (WITHIN GROUP) parameter. But the current implementation restricts use of VARIADIC in two ways:

  1. Ordered-set aggregates can only use VARIADIC "any", not other variadic array types.
  2. If the last direct parameter is VARIADIC "any", then there can be only one aggregated parameter and it must also be VARIADIC "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.) 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. ๐Ÿ™ˆ

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. ๐Ÿ’…


โœจ EXAMPLES โœจ

See Section 36.12. ๐Ÿ‘‘


โœจ COMPATIBILITY โœจ

CREATE AGGREGATE is a PostgreSQL language extension. The SQL standard does not provide for user-defined aggregate functions. So yeah โ€” this is a PostgreSQL original, no cap. ๐ŸŒˆ


โœจ SEE ALSO โœจ


And that's the page, bestie. This whole thing is from PostgreSQL 18.6, dated 2026, and it's the CREATE AGGREGATE(7) manual page. You absolutely ate that read. ๐Ÿ’–โœจ๐ŸŽ€

๐Ÿ“ฆ where this page comes from