Question

How do I find the maximum (or minimum) element of a 3-dimensional array in PostgreSQL?

Is there any function or faster way instead of this?:

min:= A[1][1][1];

for i IN 1..9 LOOP
for j IN 1..9 LOOP
for k IN 1..9 LOOP
        min := least(min,A[i][j][k]);
END LOOP;
END LOOP;
END LOOP;
Was it helpful?

Solution

Use unnest():

SELECT min(elem) AS min_elem
FROM   unnest(my_arr) AS elem

unnest() returns a set of base elements regardless of array dimensions. Then all you need is the aggregate function min().

As plpgsql assignment (since you seem to be working with plpgsql):

SELECT min(elem) INTO my_variable
FROM   unnest(my_arr) AS elem
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top