Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple data types array in PostgreSQL

Tags:

sql

postgresql

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?

like image 661
Matoe Avatar asked Nov 17 '11 13:11

Matoe


People also ask

Is array a data type in PostgreSQL?

PostgreSQL allows columns of a table to be defined as variable-length multidimensional arrays. Arrays of any built-in or user-defined base type, enum type, composite type, range type, or domain can be created.

How do I create an array in PostgreSQL?

To create a column of an array type, the [] symbol is used. The following examples illustrate this: create table contacts ( first_name varchar, last_name varchar, phone_numbers varchar[] ); create table player_scores ( player_number integer, round_scores integer[] );

Should you use arrays in Postgres?

When you are considering portability (e.g. rewriting your system to work with other databses) then you must not use arrays. If you are sure you'll stick with Postgres, then you can safely use arrays where you find appropriate. They exist for a reason and are neither bad design nor non-compliant.

What is text [] in PostgreSQL?

PostgreSQL supports a character data type called TEXT. This data type is used to store character of unlimited length. It is represented as text in PostgreSQL. The performance of the varchar (without n) and text are the same.


1 Answers

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.

like image 75
ig0774 Avatar answered Oct 06 '22 00:10

ig0774