CREATE_AGGREGATE(7pg17)
π 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:INorVARIADIC. (Aggregate functions do not supportOUTarguments, periodt.) If you omit it, the default isIN. And only the last argument can be markedVARIADICβ 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 forCREATE AGGREGATE, the input data type gets specified by abasetypeparameter 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 thebasetypeas"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,sfuncmust 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. 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 thestate_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 typestate_data_type. The return data type of the aggregate is defined as the return type of this function. If you don't specifyffunc, 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.
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_ONLYindicates it does not; the other two values indicate that it may change the transition state value. See Notes below for more detail. Default isREAD_ONLYβ except for ordered-set aggregates, where the default isREAD_WRITE. πcombinefuncβ thecombinefuncfunction may optionally be specified to allow the aggregate function to support partial aggregation. If provided,combinefuncmust 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. Think of it as ansfunc, 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 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 β they're a package deal. π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 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 typestate_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 typemstate_data_type, which might be different fromstate_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 asmsfunc, 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 asstate_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 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. Consistency is key, bestie. β¨MFINALFUNC_MODIFY = { READ_ONLY | SHAREABLE | READ_WRITE }β this option is likeFINALFUNC_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 asinitial_condition.sort_operatorβ the associated sort operator for aMIN- orMAX-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 ofPARALLEL SAFE,PARALLEL RESTRICTED, andPARALLEL UNSAFEare the same as inCREATE FUNCTION. An aggregate will not be considered for parallelization if it's markedPARALLEL UNSAFE(which is the default!) orPARALLEL 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. TheHYPOTHETICALflag 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:
- Ordered-set aggregates can only use
VARIADIC "any"β not other variadic array types. Sorry to the other 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. 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 includeDISTINCTorORDER BYclauses, 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 π¦
ALTER AGGREGATE(ALTER_AGGREGATE(7))DROP AGGREGATE(DROP_AGGREGATE(7))
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
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-160000.1.1 Β· PostgreSQL
- opensuse-leap 16.0: postgresql17 17.11-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