I've created a function which is called when a trigger is fired while insert. But every time I try to insert the data in the table I get the duplicate key value violates unique constraint
This is my trigger function:
CREATE OR REPLACE FUNCTION trg_new_rows()
RETURNS trigger AS
$BODY$
BEGIN
IF EXISTS (SELECT 1 FROM organization WHERE organization.name = 'TV' AND organization.country = 'D') THEN
--RAISE '1';
INSERT INTO organization VALUES ('TV1','TV1',NULL,'TV1',NULL,NULL);
ELSE
--RAISE '2';
INSERT INTO organization VALUES ('Tivoli1','Tivoli1 organization',NULL,'F',NULL,NULL);
INSERT INTO organization VALUES ('Tivoli2','Tivoli2 organization',NULL,'GB',NULL,NULL);
END IF;
RETURN NULL;
END;
$BODY$
LANGUAGE plpgsql VOLATILE;
And this is the trigger
CREATE TRIGGER delaft
AFTER INSERT
ON organization
FOR EACH ROW
EXECUTE PROCEDURE trg_new_rows();
And then when I try executing this:
INSERT INTO organization VALUES ('TV','Tivoli D organization',NULL,'D',NULL,NULL);
I get this error:
ERROR: duplicate key value violates unique constraint "organization_pkey"
DETAIL: Key (abbreviation)=(Tivoli1) already exists.
CONTEXT: SQL statement "INSERT INTO organization VALUES ('Tivoli1','Tivoli1 organization',NULL,'F',NULL,NULL)"
PL/pgSQL function trg_new_rows() line 8 at SQL statement
SQL statement "INSERT INTO organization VALUES ('Tivoli1','Tivoli1 organization',NULL,'F',NULL,NULL)"
PL/pgSQL function trg_new_rows() line 8 at SQL statement
, Time: 0.000000s
Although when I check the organization table I can't find any abbreviation having the value Tivoli1
. Any advice please?
This is the create and insert queries for table organization:
CREATE TABLE Organization
(Abbreviation VARCHAR(12) PRIMARY KEY,
Name VARCHAR(80) NOT NULL,
City VARCHAR(35) ,
Country VARCHAR(4) ,
Province VARCHAR(35) ,
Established DATE,
CONSTRAINT OrgNameUnique UNIQUE (Name));
INSERT INTO organization VALUES ('EFTA','European Free Trade Association','Geneva','CH','Geneve','1960-01-04');
INSERT INTO organization VALUES ('EIB','European Investment Bank','Luxembourg','L','Luxembourg','1957-03-25');
INSERT INTO organization VALUES ('CERN','European Organization for Nuclear Research','Geneva','CH','Geneve','1953-07-01');
INSERT INTO organization VALUES ('ESA','European Space Agency','Paris','F','Ile de France','1973-07-31');
INSERT INTO organization VALUES ('EU','European Union','Brussels','B','Brabant','1992-02-07');
INSERT INTO organization VALUES ('FAO','Food and Agriculture Organization','Rome','I','Lazio','1945-10-16');
I'm using navicat for postgresql.