Re: Conditional INSERT: if not exists

From: "Phillip Smith" <phillips(at)weatherbeeta(dot)com(dot)au>
To: <pgsql-novice(at)postgresql(dot)org>
Subject: Re: Conditional INSERT: if not exists
Date: 2006-08-22 01:20:40
Message-ID: 004201c6c589$2e9d9af0$9b0014ac@ITPhil
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: 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(at)postgresql(dot)org
[mailto:pgsql-novice-owner(at)postgresql(dot)org] On Behalf Of Don Morrison
Sent: Tuesday, 22 August 2006 10:43
To: pgsql-novice(at)postgresql(dot)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

In response to

Browse pgsql-novice by date

  From Date Subject
Next Message Sean Davis 2006-08-22 13:26:37 Re: Conditional INSERT: if not exists
Previous Message Don Morrison 2006-08-22 00:43:07 Conditional INSERT: if not exists