Re: Deleting conflicting rows when creating a foreign key

From: Craig Ringer <craig(at)postnewspapers(dot)com(dot)au>
To: Richard Huxton <dev(at)archonet(dot)com>
Cc: Igor Katson <descentspb(at)gmail(dot)com>, pgsql-general(at)postgresql(dot)org
Subject: Re: Deleting conflicting rows when creating a foreign key
Date: 2009-02-11 04:30:39
Message-ID: 4992546F.2070408@postnewspapers.com.au
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Richard Huxton wrote:

> DELETE FROM table1 WHERE col1 NOT IN (SELECT id from table2);

Just as a side note: If you have a large number of missing IDs and don't
want to wait a long time, you may be better off with something like
(untested, but I think it's right - TEST FIRST):

SELECT *
FROM table1 t1 LEFT OUTER JOIN table2 t2 ON (t1.ref_col=t2.id)
WHERE t2.id IS NULL;

-- check that the rows to be deleted are OK

DELETE FROM table1
USING table1 t1 LEFT OUTER JOIN table2 t2 ON (t1.ref_col=t2.id)
WHERE table1.id = t1.id AND t2.id IS NULL;

(by the way, being able to specify an explicit join method in a DELETE
... USING or update ... USING would be *great*).

--
Craig Ringer

In response to

Responses

Browse pgsql-general by date

  From Date Subject
Next Message Craig Ringer 2009-02-11 04:35:52 Re: Slow cross-machine read on one table
Previous Message Pavel Stehule 2009-02-11 04:21:08 Re: Referencing Cursor/Row/Record Fields in PL/PgSQL