Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

insert into array of custom type in Postgres

Tags:

sql

postgresql

i have created a custom Postgres type with :

CREATE TYPE new_type AS (new_date timestamp, some_int bigint);

i have a table that store arrays of new_type like:

CREATE TABLE new_table (
    table_id uuid primary key,
    new_type_list new_type[] not null
)

and i insert data in this table with something like this:

INSERT INTO new_table VALUES (
    '*inApplicationGeneratedRandomUUID*',
    ARRAY[[NOW()::timestamp, '146252'::bigint],
          [NOW()::timestamp, '526685'::bigint]]::new_type[]
)

and i get this error

ERROR: cannot cast type timestamp without time zone to new_type

What am I missing? I've also tried array syntax that uses {} but nothing better.

like image 540
Nils Avatar asked Jan 15 '17 16:01

Nils


People also ask

Can you insert array 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.

What is [] in PostgreSQL?

Array Type. PostgreSQL gives the opportunity to define a column of a table as a variable length single or multidimensional array. Arrays of any built-in or user-defined base type, enum type, or composite type can be created. We will focus on one data type in particular, the Array of text, text[].

How do I create an array in PostgreSQL?

PostgreSQL Array type PL/pgSQL in PostgreSQL allows us to declare a variable as an ARRAY type. This ARRAY can be either a base or a custom type. For example, if we want to store a list of PINCODE values, then, we can declare the variable as v_pincode INT[].

Can we insert data into view PostgreSQL?

An updatable view may contain both updatable and non-updatable columns. If you try to insert or update a non-updatable column, PostgreSQL will raise an error.


1 Answers

The easiest way would probably be:

INSERT INTO new_table VALUES (
    '9fd92c53-d0d8-4aba-8925-1bd648d565f2'::uuid,
    ARRAY[ row(now(), 146252)::new_type,
           row(now(), 526685)::new_type
     ] );

Note that you have to cast the row type to ::new_type.

As an alternative, you could also write:

INSERT INTO new_table VALUES (
    '9fd92c53-d0d8-4aba-7925-1ad648d565f2'::uuid,
    ARRAY['("now", 146252)'::new_type,
          '("now", 526685)'::new_type
     ] );

Check PostgreSQL documentation about Composite Value Input.

like image 140
joanolo Avatar answered Oct 25 '22 21:10

joanolo