12

I'm sorry if this is a duplicate, although I couldn't find an exact answer for this anywhere:
Is there a way to create an array in postgreSQL which contains multiple data types?

I have an column of type text[] (array of type text); although I'd like to insert into this array three text entries and then a fourth entry, from type integer.

Is there a way to do so? If so, how?

1 Answer 1

20

I don't believe there's a way to declare an array with multiple types; however, I think you can accomplish what you are trying to do with a composite type, e.g.,

create type my_item as (
    field_1        text,
    field_2        text,
    field_3        text,
    field_4        number
);

You could then use this as the column type for your table or even declare a column of arrays of my_item[] if that fits your need.

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

2 Comments

Should I write this code in python file? or inside postgres? (if yes where? )
You CAN use JSON(B) to accomplish this task. Ex: SELECT '[1, "text", true]'::JSONB; but there are limitations with that, namely that JSON only supports a limited number of data types which don't match 1:1 with postgres' native data types. But it is a quick basic solution that isn't necessarily hacky.

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.