UPD: the error explanation is marked as correct answer. Here is final solution that worked for me
REATE OR REPLACE FUNCTION calculate_snapshot_internal(_this_value bigint, _next_value bigint, _next_value_type int, OUT _code bigint) LANGUAGE plpgsql AS $func$ BEGIN if _next_value is null then _code = _this_value; -- just pass by whatever it has, null means missing value elseif _next_value_type = 1 or _next_value_type = 2 then -- SNAPSHOT value _code = _next_value; elseif _next_value_type = 0 and _this_value is not null then -- Add INCREMENT value to accumulated value _code = _this_value + _next_value; end if; END $func$; drop aggregate if exists calculate_snapshot(bigint, int); CREATE aggregate calculate_snapshot(bigint, int) ( sfunc = calculate_snapshot_internal, stype = bigint );