1

postgres supports multi dimensional arrays, however the length is restricted.

CREATE TABLE test (
    field1 text[][]
);

INSERT INTO test VALUES ('{{null, null}, {foo, null}, {foo, bar}}');

this works fine, but if I do

INSERT INTO test VALUES ('{{}, {foo}, {foo, bar}}');

this gives an error 'malformed array literal: "{{}, {foo}, {foo, bar}}"'. Can I do something like the above but without errors?

3
  • I have a hard time finding justification for de-normalizing using single dimension arrays. The use case for de-normalizing a model using a 2d array seem even smaller. Commented Aug 26, 2021 at 5:33
  • We can break it down to another table but the overall structure of the database is complicated enough so a 2d array will be easier for our implementation and maintenance Commented Aug 26, 2021 at 7:08
  • e.g. a 2d array representing Intersection/union of groups of elements [[a], [b, c]] -> a ∩ (b ∩ c) Commented Aug 26, 2021 at 7:15

1 Answer 1

1

You could use a domain:

CREATE DOMAIN x AS text[];

CREATE TABLE test (field1 x[]);

INSERT INTO test VALUES (ARRAY[
                            ARRAY[]::x,
                            ARRAY['foo']::x,
                            ARRAY['foo', 'bar']::x
                         ]);

TABLE test;

           field1           
════════════════════════════
 {"{}","{foo}","{foo,bar}"}
(1 row)
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way to insert by literal constant? Because I'm using Hasura and it only works with array literal
Sure, use the exact format of the final query result.

Your Answer

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.