Re: Deleting conflicting rows when creating a foreign key

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

Craig Ringer wrote:
> 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
>
Thanks for the advice, Craig, I didn't know about that syntax before.

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Dave Page 2009-02-11 09:32:05 Re: Key Vs Index
Previous Message Richard Huxton 2009-02-11 08:32:56 Re: Difference between Windows pgsql and Linux pgsql?