From: C. Bensend <benny@bennyvision.com>
To: pgsql-sql@postgresql.org
Subject: Inserting into table only if the row does not already exist.
Date: Thu, 14 Oct 2004 23:18:21 -0500 (CDT)
Message-ID: <56362.63.227.74.41.1097813923.squirrel@63.227.74.41> (raw)
Hey folks,
I am inserting data into a table with a three-column primary key (the
table is only three columns). The rows I'm trying to insert may very
well be duplicates of ones already in the table, so I would like to have
PostgreSQL handle the insert and possible error resulting from dup data.
I can certainly do a SELECT first and then INSERT if it's not a duplicate,
ala:
* Do a SELECT against the three columns
* If there are no rows returned, then do the INSERT
But I thought this would be possible with the following:
INSERT INTO table ( column1, column2, column3 )
SELECT column1, column2, column3
WHERE NOT EXISTS (
SELECT column1, column2, column3 FROM table WHERE
column1 = $column1 AND
column2 = $column2 AND
column3 = $column3 )
.. which gave me 'ERROR: column1 does not exist'. Nuts.
Is this possible to do in one statement? I checked with a DBA friend
(he's an Oracle guy), Google, and the list archives, and either didn't
find anything helpful or simply didn't try the correct search terms. Or
should I be doing this sort of thing in two separate queries?
Thanks for all the help you folks have given me,
Benny
--
"Even if a man chops off your hand with a sword, you still have two nice,
sharp bones to stick in his eyes."
-- .sig on Slashdot
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients using the --to and --cc options:
reply via email
To: pgsql-sql@postgresql.org
Cc: benny@bennyvision.com
Subject: Re: Inserting into table only if the row does not already exist.
In-Reply-To: <56362.63.227.74.41.1097813923.squirrel@63.227.74.41>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox