CREATE_AGGREGATE(7pg17)

πŸ“¦ version 17.11, in opensuse-leap 16.0

πŸ’… CREATE_AGGREGATE πŸ’…

okay so this is the CREATE AGGREGATE page from the PostgreSQL 17.11 Documentation, and it's genuinely a lot, so grab a snack πŸ“ β€” this is part one of three, bestie, don't go anywhere.


✨ NAME ✨

CREATE_AGGREGATE β€” define a new aggregate function 🫢


🌸 SYNOPSIS 🌸

so there are like, three whole ways to write this, and here's the main character one:

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

then the ordered-set / hypothetical-set glow-up πŸ¦‹:

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's still serving looks, we don't judge πŸ‘‘):

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 πŸ¦‹

okay so CREATE AGGREGATE defines a new aggregate function β€” that's the whole vibe. πŸ’–

CREATE OR REPLACE AGGREGATE will either define a brand-new aggregate function or replace an existing definition, depending on what's already there. Some basic and commonly-used aggregate functions are already included with the distribution (they're documented in Section 9.21, iykyk). But if you're out here defining new types, or you need an aggregate function that isn't already provided, then CREATE AGGREGATE is literally right there to give you the features you want. 🫢

🌈 replacing stuff (the rules)

when you're replacing an existing definition, the argument types, the result type, and the number of direct arguments may not be changed. no cap. also, the new definition must be of the same kind as the old one β€” meaning ordinary aggregate, ordered-set aggregate, or hypothetical-set aggregate. it's giving "same energy only."

πŸŽ€ where does it go

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. simple as that. ✨

πŸ’œ how aggregates get identified

an aggregate function is identified by its name and input data type(s). two aggregates in the same schema can have the same name if they operate on different input types. and the name and 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))). πŸ’…

🌸 the simple aggregate situation

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. if there's no final function, then the ending state value is returned as-is. iconic behavior honestly. ⭐

🧚 initial conditions

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 is not supplied, then the state value starts out null. πŸ™ˆ

πŸ”₯ strict vs non-strict transition functions

so 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-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 these types are different, you must supply a nonnull initial condition or use a nonstrict transition function. don't forget, bestie.

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 allows the aggregate author to have full control over the aggregate's handling of null values. main character energy: you handle your own nulls. πŸ‘‘

🌟 the final function

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, no surprises there.) 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. relatable β€” zero rows, zero results. 😭

πŸ’« FINALFUNC_EXTRA core

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. so smart. πŸ’…

lowkey a trap: FINALFUNC_EXTRA + a strict final function = no. the params come in as NULL, so the function has to be able to accept that.

πŸ¦‹ 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 like the corresponding simple-aggregate parameters without the M; they define a separate implementation of the aggregate that includes an inverse transition function. it's giving "the aggregate but make it faster." πŸ”₯

πŸŽ€ 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 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. fake row, real results. 🧚

🌈 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. both things, bestie, not just one.

⭐ MIN/MAX optimization (the sneaky 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. 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. πŸ”₯

okay important caveat: 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's just decorative. πŸ’€

πŸ‘‘ privileges, aka the entry fee

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

  • name β€” the name of the aggregate function you're creating, optionally schema-qualified. πŸŽ€
  • argmode β€” the mode of an argument: IN or VARIADIC. (Aggregate functions do not support OUT arguments, periodt.) If you omit it, the default is IN. And only the last argument can be marked VARIADIC β€” that's the rule, bestie. πŸ’…
  • argname β€” the name of an argument. Ngl this is currently only useful for documentation purposes. Skip it and the argument just has no name. πŸ€·β€β™€οΈ
  • arg_data_type β€” an input data type that this aggregate function operates on. Wanna create a zero-argument aggregate function? Write * in place of the whole list of argument specifications. (Iconic example of one of those: count(*).) ✨
  • base_type β€” in the old syntax for CREATE AGGREGATE, the input data type gets specified by a basetype parameter instead of being written next to the aggregate name. Heads up though: this syntax allows only one input parameter. And to define a zero-argument aggregate function with this syntax, you specify the basetype as "ANY" β€” not *, okay? Also ordered-set aggregates cannot be defined with the old syntax at all. 🫢
  • sfunc β€” the name of the state transition function, called for each input row. For a normal N-argument aggregate function, sfunc must take N+1 arguments β€” the first being of type state_data_type and the rest matching the declared input data type(s) of the aggregate. The function must return a value of type state_data_type. Basically it takes the current state value plus 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's the same deal.

  • 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 omit this parameter or set it to zero, a default estimate is used based on the state_data_type. The planner uses this value to estimate the memory required for a grouped aggregate query. Lowkey important for performance. ⭐
  • 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 type state_data_type. The return data type of the aggregate 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. πŸŽ€

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.

If FINALFUNC_EXTRA is 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. πŸ¦‹

  • 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_ONLY indicates it does not; the other two values indicate that it may change the transition state value. See Notes below for more detail. Default is READ_ONLY β€” except for ordered-set aggregates, where the default is READ_WRITE. πŸ“
  • combinefunc β€” the combinefunc function may optionally be specified to allow the aggregate function to support partial aggregation. If provided, combinefunc must combine two state_data_type values β€” each containing 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 upon an individual input row and adding it to the running aggregate state, it adds another aggregate state to the running state. πŸ’«

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 which 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 whose state_data_type is internal, the combinefunc must not be strict. In this case combinefunc must ensure that null states are handled correctly and that the state being returned is properly stored in the aggregate memory context. Don't skip this one, fr fr. ⚠️

  • serialfunc β€” an aggregate function whose state_data_type is internal can participate in parallel aggregation only if it has a serialfunc function, which must serialize the aggregate state into a bytea value for transmission to another process. This function must take a single argument of type internal and return type bytea. 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. (Note: the second, internal argument is unused, but it's required for type safety reasons. Annoying but valid. 😭)
  • 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 null. 🌸
  • 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 type mstate_data_type, which might be different from state_data_type. πŸ‘‘
  • 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 as msfunc, but it's used to remove a value from the current aggregate state rather than add a value to it. And the inverse transition function must have the same strictness attribute as the forward state transition function β€” no cap, they gotta match. πŸ’…
  • mstate_data_type β€” the data type for the aggregate's state value, when using moving-aggregate mode. πŸ¦‹
  • mstate_data_size β€” the approximate average size (in bytes) of the aggregate's state value, when using moving-aggregate mode. This works the same 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 using moving-aggregate mode. This works the same as ffunc, except that its first argument's type is mstate_data_type and extra dummy arguments are specified by writing MFINALFUNC_EXTRA. The aggregate result type determined by mffunc or mstate_data_type must match that determined by the aggregate's regular implementation. Consistency is key, bestie. ✨
  • MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE } β€” this option is like FINALFUNC_MODIFY, but it describes the behavior of the moving-aggregate final function. πŸŽ€
  • minitial_condition β€” the initial setting for the state value, when using moving-aggregate mode. This works the same as initial_condition.
  • 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). πŸ”₯
  • 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 is the default!) or PARALLEL RESTRICTED. Big note: the parallel-safety markings of the aggregate's support functions are not consulted by the planner β€” only the marking of the aggregate itself. So don't get it twisted. πŸ’€
  • 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. 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. πŸ€“

And the cutest part? The parameters of CREATE AGGREGATE can be written in any order β€” not just the order illustrated above. Go off, arrange them however your heart desires. 🌈🫢

🌸 NOTES 🌸

Okay bestie, this is the part where the real lore drops, so pay attention πŸ’…

When you're naming support functions in parameters, you can write a schema name if you need to β€” like SFUNC = public.sum. But do NOT write argument types in there, okay? The argument types of the support functions get figured out from the other parameters. Not your job. Let the system cook ✨


So like, normally PostgreSQL functions are expected to be true functions β€” the well-behaved kind that don't modify their input values πŸŽ€ But a transition function for an aggregate, when it's used in the context of an aggregate, is allowed to cheat and modify its transition-state argument in place. In place!! Lowkey iconic πŸ™ˆ And it gives you substantial performance benefits compared to making a fresh copy of the transition state every single time. The way that copy is just... unnecessary. We love efficiency πŸ’–

Same sort of deal with final functions: an aggregate final function is normally expected not to modify its input values, but sometimes it's straight-up impractical to avoid modifying the transition-state argument 😭 When that happens, you must declare that behavior using the FINALFUNC_MODIFY parameter. Here's the tea on the two values:

  • READ_WRITE β€” says 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. No merging for you 🚫
  • SHAREABLE β€” says 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 πŸ‘‘

And the parenthetical clarification, because it matters: the optimization of interest here is not applying the same final function repeatedly β€” it's applying different final functions to the same ending transition state value. That's allowed as long as none of the final functions are marked READ_WRITE 🫢


Now, moving-aggregate mode πŸ¦‹ If an aggregate supports it, it improves calculation efficiency when the aggregate is used as a window function for a window with a moving frame start β€” that is, a frame start mode other than UNBOUNDED PRECEDING. Conceptually it's giving very much in-and-out energy: 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 get removed, they're always removed in the same order they were added. Periodt.

Whenever the inverse transition function is invoked, it will thus receive the earliest added but not yet removed argument value(s). And the inverse transition function can assume that at least one row will remain in the current state after it removes the oldest row. (When that wouldn't be the case, the window function mechanism simply starts a fresh aggregation instead of using the inverse transition function β€” no drama, just a reset πŸ’…)

Heads up ⚠️: 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 gets redone from scratch for the current frame starting position. This convention is what lets moving-aggregate mode be used in situations where there are some infrequent cases that are impractical to reverse out of the running state value. Very "we'll just start over, it's fine" of it 😌


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; that's done by continuing to add new values to the aggregate's state. And this 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 continue even after an aggregate result value has been obtained for one set of frame boundaries. Protecting the state's peace 🫢


Ordered-set aggregate time, and the syntax here is spicy 🌢️ 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:

  1. Ordered-set aggregates can only use VARIADIC "any" β€” not other variadic array types. Sorry to the other 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. RIP to pg_proc's limitations πŸ™ˆ)

And 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. iykyk ✨

Currently, ordered-set aggregates do not need to support moving-aggregate mode, since they cannot be used as window functions. No window, no moving-aggregate era πŸŽ€

Also, partial (including parallel) aggregation is currently not supported for ordered-set aggregates. And it will never be used for aggregate calls that include DISTINCT or ORDER BY clauses, since those semantics cannot be supported during partial aggregation. Not now, not ever, fr fr πŸ’€

✨ EXAMPLES ✨

See Section 36.12. That's the whole section, bestie β€” go read the chapter, it's got the whole tutorial arc 🌈


πŸ’œ COMPATIBILITY πŸ’œ

CREATE AGGREGATE is a PostgreSQL language extension. The SQL standard does not provide for user-defined aggregate functions. So like... the standard simply did not think of this. Their loss, honestly πŸ‘‘


πŸ¦‹ SEE ALSO πŸ¦‹


That's the whole page, bestie β€” go forth and aggregate 🌸🫢 This was pulled straight from PostgreSQL 17.11, dated 2026, and the page itself is CREATE AGGREGATE(7). Slay πŸ’…βœ¨

πŸ“¦ where this page comes from