1

Say I have a table results that contains a score column that is an array full of scores:

CREATE TABLE results (
  id serial PRIMARY KEY,
  scores numeric[]
);

I would like to update the table so that I round each score to 4 decimal places.

I have created a rounding function round_numeric_array that works for a single array value:

CREATE OR REPLACE FUNCTION round_numeric_array (numeric[]) RETURNS numeric[]
LANGUAGE SQL
AS $$
   SELECT array_agg(round(unnest($1), 4))
$$;

But how do I apply it to every value in the table? I've been trying

UPDATE results SET scores = round_numeric_array(scores)

But I get a set-valued function called in context that cannot accept a set error. Any ideas?

1 Answer 1

5

Place the unnest() function in the FROM clause:

CREATE OR REPLACE FUNCTION round_numeric_array (numeric[]) 
RETURNS numeric[]
IMMUTABLE
LANGUAGE SQL 
AS $$
   SELECT array_agg(round(elem, 4))
   FROM unnest($1) as arr(elem);
$$;

Note, that the function is immutable, read more in the documentation.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.