Search code examples
arrayspostgresqlinsertcreate-tablesql-types

Insert data into user-defined type elements of a table in postgresql


I have defined 3 types as follow:

CREATE TYPE EventDescriptionType AS ENUM (
 'felt report',
 'Flinn-Engdahl region',
 'local time',
 'tectonic summary',
 'nearest cities',
 'earthquake name',
 'region name'
);

CREATE TYPE ResourceReference AS (
  "resourceID" varchar(255)  
);

CREATE TYPE EventDescription AS (
 "text" text,
 "type" EventDescriptionType
);

Also I have created a table with elements of above type:

CREATE TABLE Event (
 "Event_id"                   serial PRIMARY KEY,
 "description"                EventDescription ARRAY
);

Then, after inserting some data into this table by this command:

insert into Event values (1,'{'L','felt report'}');

I got this error:

ERROR: syntax error at or near "L"
LINE 1: insert into Event values (1,'{'L','felt report'}');

For Element "dexcription" in the Event table I passed '1' as event_id and 'L' & 'felt report' in an array for for "text" and "type" of EventDescription Type, respectively.

Can someone please let me know the correct way to do this? Any help would be appreciated.


Solution

  • You need to cast the array type as EventDescription[]

    insert into Event values (1,
                              ARRAY[('L','felt report')]::EventDescription[]
                              );
    

    sqlfiddle