1

I have a 2D array which looks like below

[['2018-05-15', 6.7580658761256265], ['2018-05-16', 7.413963464926804], ['2018-05-17', 8.801776892107043], ['2018-05-18', 10.292505686766823], ['2018-05-19', 10.292505686766823], ['2018-05-20', 10.292505686766823], ['2018-05-21', 10.292505686766823]]

I want to store this 2D array in postgres.I checked postgres's documentation https://www.postgresql.org/docs/9.1/static/arrays.html and found the below example

CREATE TABLE sal_emp (
    name            text,
    pay_by_quarter  integer[],
    schedule        text[][]
);

INSERT INTO sal_emp
    VALUES ('Bill',
    ARRAY[10000, 10000, 10000, 10000],
    ARRAY[['meeting', 'lunch'], ['training', 'presentation']]);

For a list that contains both of its values as string ['meeting', 'lunch'], we use text[][] But as you can see, I have one string and one float as a content of a list

['2018-05-15', 6.7580658761256265]

Then what do I set the column type as?

1

1 Answer 1

5

It's not an array anymore if the types are different. Arrays only can have one base type. You'll have to use an array of a composite type instead.

CREATE TYPE your_type AS (text_member text,
                          float_member float);

CREATE TABLE your_table
             (your_type_column your_type[]);

INSERT INTO your_table
            (your_type_column)
            VALUES (array[row('2018-05-15',
                              6.7580658761256265)::your_type,
                          row('2018-05-16',
                              7.413963464926804)::your_type,
                          ...
                          row('2018-05-21',
                              10.292505686766823)::your_type]);

But maybe consider not using arrays at all if possible, have another table and a normalized schema. Also consider using date instead of text if it's actually a date. (I just used text because you said it was a "string", though the sample data suggests differently.)

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

Comments

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.