I'm new to Postgresql (I'm programming in PL/pgSQL, there's no much difference with sql). I wrote my custome aggregate function, which has to find the min value, or max in an array of numeric. This is the function aggregate code
CREATE OR REPLACE FUNCTION searchMaxValue (numeric[]) RETURNS numeric AS $$
DECLARE
i numeric;
maxVal numeric;
BEGIN
maxVal = $1[1];
IF ARRAY_LENGHT($1,1) > 0 THEN --Checking whether the array is empty or not
<<confrontoMassimo>>
FOREACH i IN ARRAY $1 LOOP --Looping through the entire array, passed as parameter
IF maxVal <= $1[i] THEN
maxVal := $1[i];
END IF;
END LOOP confrontoMassimo;
ELSE
RAISE NOTICE 'Invalid parameter % passed to the aggregate function',$1;
--Raising exception if the parameter passed as argument points to null.
RAISE EXCEPTION 'Cannot find Max value. Parameter % is null', $1
USING HINT = 'You cannot pass a null array! Check the passed parameter';
END IF;
RETURN maxVal;
END;
$$ LANGUAGE plpgsql;
CREATE AGGREGATE searchMaxValueArray (numeric)
(
sfunc = array_append,
stype = numeric[],
finalfunc = searchMaxValue,
initCond = '{}'
);
The problem is, that it doesn't work as expected. What is the problem?
ARRAY_LENGHTshould beARRAY_LENGTH. Is it just a typo or your issue is related to that ?unnestalong withMAX/MINto accomplish this? i.e.:select MAX(id) FROM unnest(ARRAY[1,2,3]) AS t(id);sfuncrather than infinalfunc, the array could become too large to handle. I see no fundamental problem with your function, please describe the malfunction.