3

In my parameterized query I have to unnest arrays with 1 dimension and 2 dimensions:

$1: ARRAY['id1', 'id2']
$2: ARRAY[ARRAY['tag1'], ARRAY['tag2']]

I tried this query:

INSERT INTO table (id, tags)
SELECT * FROM UNNEST ($1::text[], $2::text[][])

But got this error:

column "tags" is of type text[] but expression is of type text 

I want the result of SELECT * FROM UNNEST ... to be 2 rows:

'id1', ARRAY['tag1']
'id2', ARRAY['tag2']

1 Answer 1

2

To unnest 1-dimensional arrays from N-dimensional arrays, I suggest this custom function:

CREATE OR REPLACE FUNCTION unnest_nd_1d(a ANYARRAY, OUT a_1d ANYARRAY)
  RETURNS SETOF ANYARRAY
  LANGUAGE plpgsql IMMUTABLE PARALLEL SAFE STRICT AS
$func$
BEGIN
   FOREACH a_1d SLICE 1 IN ARRAY a_2d LOOP
      RETURN NEXT;
   END LOOP;
END
$func$;

See:

Then to achieve your desired result:

SELECT unnest(a1), unnest_nd_1d(a2)
FROM  (
   SELECT '{id1,id2}'::text[]
        , '{{tag1},{tag2}}'::text[]
   ) t(a1, a2);

db<>fiddle here

About those multiple set-returning functions in the SELECT list:

Your use of text[][] indicates a misunderstanding. Postgres does not enforce array dimensions. See:

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.