Re: Deleting conflicting rows when creating a foreign key

From: Richard Huxton <dev(at)archonet(dot)com>
To: Igor Katson <descentspb(at)gmail(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Deleting conflicting rows when creating a foreign key
Date: 2009-02-10 14:46:42
Message-ID: 49919352.3000603@archonet.com
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Igor Katson wrote:
> I am doing an ALTER TABLE to create a foreign key, however with some
> rows i get:
>
> insert or update on table "name" violates foreign key constraint
> "name_fkey"
>
> How can I just drop the conflicting rows while doing that?

You can't automatically. You can do something like:

BEGIN;
SELECT * FROM table1 WHERE col1 NOT IN (SELECT id from table2);
-- check results are as you'd expect
DELETE FROM table1 WHERE col1 NOT IN (SELECT id from table2);
ALTER TABLE table1 ADD CONSTRAINT ... FOREIGN KEY ...
COMMIT;

--
Richard Huxton
Archonet Ltd

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message SHARMILA JOTHIRAJAH 2009-02-10 15:07:42 Good Delimiter for copy command
Previous Message Richard Huxton 2009-02-10 14:43:44 Re: Slow database creation