Re: Conditional INSERT: if not exists - Mailing list pgsql-novice

From Phillip Smith
Subject Re: Conditional INSERT: if not exists
Date
Msg-id 004201c6c589$2e9d9af0$9b0014ac@ITPhil
Whole thread Raw
In response to Conditional INSERT: if not exists  ("Don Morrison" <donmorrison@gmail.com>)
List pgsql-novice
One way would be to create a Primary Index containing all columns in the
table...?

For example - a table called "grps" with 3 colums:
    CREATE TABLE grps
    (
      code varchar(4) NOT NULL,
      description text NOT NULL,
      category varchar(3),
      CONSTRAINT groups_pkey PRIMARY KEY (code,description,category)
    )

An insert on this table will fail if the values for each column in the row
you are attempting to insert already matches and existing row - Example:

 code |              description               | category
------+----------------------------------------+----------
 0001 | GROUP NOT DEFINED                      | OT1
 0009 | NEWLY CREATED PRODUCTS                 | OT1
 0010 | GROUP NOT SET                          | OT1

Then attempting:
    INSERT INTO grps VALUES ('0001', 'GROUP NOT DEFINED', 'OT1');
This will fail as it already matches the first row in the table.

This WILL work (with a different value in the third column):
    INSERT INTO grps VALUES ('0001', 'GROUP NOT DEFINED', 'OT2');

Cheers,
-p


-----Original Message-----
From: pgsql-novice-owner@postgresql.org
[mailto:pgsql-novice-owner@postgresql.org] On Behalf Of Don Morrison
Sent: Tuesday, 22 August 2006 10:43
To: pgsql-novice@postgresql.org
Subject: [NOVICE] Conditional INSERT: if not exists

I want to insert a row unless it exists already.  Do I have to write a
stored procedure to do this?

Thanks,
Don

---------------------------(end of broadcast)---------------------------
TIP 4: Have you searched our list archives?

               http://archives.postgresql.org


*******************Confidentiality and Privilege Notice*******************

The material contained in this message is privileged and confidential to
the addressee.  If you are not the addressee indicated in this message or
responsible for delivery of the message to such person, you may not copy
or deliver this message to anyone, and you should destroy it and kindly
notify the sender by reply email.

Information in this message that does not relate to the official business
of Weatherbeeta must be treated as neither given nor endorsed by Weatherbeeta.
Weatherbeeta, its employees, contractors or associates shall not be liable
for direct, indirect or consequential loss arising from transmission of this
message or any attachments

pgsql-novice by date:

Previous
From: Sean Davis
Date:
Subject: Re: Conditional INSERT: if not exists
Next
From: "ben sewell"
Date:
Subject: Passing parameters to postgreSQL from MS Access 2000