CREATE AGGREGATE With SFUNC And FINALFUNC

Define a custom PostgreSQL aggregate using CREATE AGGREGATE with a state type, SFUNC, INITCOND, and FINALFUNC that works in GROUP BY and OVER frames.

SqlData Integrity

Code

snippet
CREATE TYPE pg_temp.mul_state AS (
    prod numeric,
    seen boolean
);

CREATE FUNCTION pg_temp.mul_step(state pg_temp.mul_state, val numeric)
RETURNS pg_temp.mul_state
LANGUAGE sql
IMMUTABLE AS $$
    SELECT CASE
        WHEN val IS NULL THEN state
        ELSE ROW(state.prod * val, true)::pg_temp.mul_state
    END;
$$;

CREATE FUNCTION pg_temp.mul_final(state pg_temp.mul_state)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
STRICT AS $$
    SELECT CASE WHEN state.seen THEN ROUND(state.prod, 4) ELSE NULL END;
$$;

-- Handles negatives, zero, and NULL inputs across both GROUP BY and window frames
CREATE AGGREGATE pg_temp.mul_agg(numeric) (
    SFUNC = pg_temp.mul_step,
    STYPE = pg_temp.mul_state,
    FINALFUNC = pg_temp.mul_final,
    INITCOND = '(1,f)'
);

CREATE TEMP TABLE factor_steps (
    series text NOT NULL,
    step   integer NOT NULL,
    factor numeric
);

INSERT INTO factor_steps VALUES
    ('a', 1,  1.50),
    ('a', 2, -2.00),
    ('a', 3,  NULL),
    ('b', 1,  3.00),
    ('b', 2,  0.00),
    ('c', 1,  NULL);

SELECT
    series,
    step,
    factor,
    pg_temp.mul_agg(factor) OVER (PARTITION BY series ORDER BY step) AS running_product,
    pg_temp.mul_agg(factor) OVER (PARTITION BY series) AS series_product
FROM factor_steps
ORDER BY series, step;

SELECT
    series,
    pg_temp.mul_agg(factor) AS grouped_product
FROM factor_steps
GROUP BY series
ORDER BY series;

Code flow overview — CREATE AGGREGATE With SFUNC And FINALFUNC

The file runs SELECT / INSERT / CREATE statements, touching factor_steps.

factor_steps creates isolated per-session scratch tables directly inside this SQL script so zero prior schema state is needed and cleanup completes upon disconnect.

Concretely, the SQL combines: a GROUP BY that collapses matching rows into one output row per group; a window function (OVER (…)) deriving row-adjacent metrics across partitions while keeping every input tuple distinct; an ORDER BY that fixes the output order; NOT NULL qualifiers on the required columns.

Caveats

  • Window functions evaluate after WHERE/GROUP BY, so filtering on their output in the same-level WHERE will not work — use an outer query or a CTE.

Putting it to use

Nothing outside the file is needed: the session-local tables it touches (factor_steps) are created by the file itself — point it at a scratch database and run the whole thing.

Core lines

SELECT
    series,
    step,
    factor,
    pg_temp.mul_agg(factor) OVER (PARTITION BY series ORDER BY step) AS running_product,
    pg_temp.mul_agg(factor) OVER (PARTITION BY series) AS series_product
FROM factor_steps
ORDER BY series, step;
CREATE FUNCTION pg_temp.mul_step(state pg_temp.mul_state, val numeric)
RETURNS pg_temp.mul_state
LANGUAGE sql
IMMUTABLE AS $$
    SELECT CASE
        WHEN val IS NULL THEN state
        ELSE ROW(state.prod * val, true)::pg_temp.mul_state
    END;
$$;
CREATE FUNCTION pg_temp.mul_final(state pg_temp.mul_state)
RETURNS numeric
LANGUAGE sql
IMMUTABLE
STRICT AS $$
    SELECT CASE WHEN state.seen THEN ROUND(state.prod, 4) ELSE NULL END;
$$;

Interactive Tools for This Topic

FAQ

What relations does the SQL touch?
`factor_steps`.