The idea · Lab 3.7.3A geometric mean is not a built-in PostgreSQL aggregate — but CREATE AGGREGATE genuinely lets any engineer add one directly in SQL, with just a state-transition function and a final function. This lab writes a real geomean(float8) aggregate and verifies it against a compounding-investment-returns calculation with a known, independently-computable correct answer — not just checking that it runs, but that it is right.
Two further aggregate classes are already built into PostgreSQL and are frequently unknown even to experienced engineers: ordered-set aggregates like percentile_cont() and percentile_disc(), which need an explicit WITHIN GROUP (ORDER BY ...) clause since their result genuinely depends on row order, not just row values; and hypothetical-set aggregates like rank() WITHIN GROUP, which compute what a value's rank would be without ever inserting it.
A Real, From-Scratch Aggregate
CREATE FUNCTION geomean_sfunc(state float8[], val float8) RETURNS float8[] AS
$$ SELECT ARRAY[state[1] + ln(val), state[2] + 1] $$ LANGUAGE sql;
CREATE FUNCTION geomean_ffunc(state float8[]) RETURNS float8 AS
$$ SELECT exp(state[1] / state[2]) $$ LANGUAGE sql;
CREATE AGGREGATE geomean(float8) (
sfunc = geomean_sfunc, stype = float8[], finalfunc = geomean_ffunc, initcond = '{0,0}'
);
The state tracks a running sum of logarithms and a running count in a two-element array; the final function converts back with exp(sum/count) — the standard, real way to compute a geometric mean incrementally.
Verified Against a Known Answer
SELECT geomean(x) FROM (VALUES (1.10::float8),(1.20),(0.95)) AS t(x); -- 1.078365153390936
SELECT (1.10*1.20*0.95)^(1.0/3.0); -- 1.07836515339093589945
Both genuinely agree — the aggregate is not just running without error, it is computing the mathematically correct compounding return.
Ordered-Set Aggregates: percentile_cont vs percentile_disc
SELECT percentile_cont(ARRAY[0.25,0.5,0.75]) WITHIN GROUP (ORDER BY x) FROM generate_series(1,100) x;
-- {25.75,50.5,75.25} <- interpolated between actual values
SELECT percentile_disc(0.95) WITHIN GROUP (ORDER BY x) FROM generate_series(1,100) x;
-- 95 <- an actual value that exists in the data
percentile_cont() interpolates between the two nearest real values; percentile_disc() always returns an actual value that genuinely exists in the input — the real, meaningful difference between them.
Hypothetical-Set Aggregates: rank() Without Inserting Anything
SELECT rank(105) WITHIN GROUP (ORDER BY x) FROM generate_series(1,100) x; -- 101
105 does not exist in the series at all — rank() genuinely computed what its rank would be if it were inserted, with zero actual modification to any data.
Key concepts
CREATE AGGREGATE (sfunc, stype, finalfunc)
sfunc is called once per input row, folding the new value into a running state of type stype; finalfunc (optional) transforms that final state into the aggregate's real result. This lab's geomean tracks a running [sum of logarithms, count] pair as its state, and finalfunc converts it back with exp(sum/count) — the standard incremental technique for a geometric mean, verified directly against a known answer.
Ordered-set aggregate (WITHIN GROUP ORDER BY)
A class of aggregate whose result genuinely depends on the order of its inputs, not just their values — percentile_cont() and percentile_disc() are the standard examples, requiring an explicit WITHIN GROUP (ORDER BY ...) clause rather than a plain argument list.
Hypothetical-set aggregate
A further variant of ordered-set aggregate that computes what a value's rank or percentile would be if it were added to the existing ordered set, without ever actually inserting it — rank() WITHIN GROUP is the standard example, confirmed directly in this lab to correctly compute the rank of a value that does not exist anywhere in the underlying data.
What to remember
- CREATE AGGREGATE lets any engineer add a real, missing aggregate directly in SQL, using only an sfunc and (optionally) a finalfunc
- A custom aggregate is only trustworthy once verified against an independently-computable known answer, not just confirmed to run without error
- percentile_cont() interpolates between real neighboring values; percentile_disc() always returns an actual value genuinely present in the data — a real, meaningful difference, not just an implementation detail
- A hypothetical-set aggregate like rank() WITHIN GROUP computes what a value's real rank would be without ever inserting it, answering a "what if" question with zero data modification
- All three techniques answer real finance/risk/sales questions entirely inside PostgreSQL, with no data ever needing to leave the database