Received: from maia.hub.org (unknown [200.46.208.211]) by mail.postgresql.org (Postfix) with ESMTP id DCD5D6326EB for ; Thu, 4 Mar 2010 06:57:01 -0400 (AST) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.208.211]) (amavisd-maia, port 10024) with ESMTP id 39366-02 for ; Thu, 4 Mar 2010 10:56:45 +0000 (UTC) X-Greylist: delayed 00:05:30.852698 by SQLgrey-1.7.6 Received: from mx01.bfk.de (mx01.bfk.de [193.227.124.2]) by mail.postgresql.org (Postfix) with ESMTP id 3A8106326D7 for ; Thu, 4 Mar 2010 06:56:51 -0400 (AST) Received: from mx00.int.bfk.de ([10.119.110.2]) by mx01.bfk.de with esmtps (TLS1.0:RSA_AES_256_CBC_SHA1:32) id 1Nn8eB-00087D-Db for pgsql-sql@postgresql.org; Thu, 04 Mar 2010 10:51:15 +0000 Received: by bfk.de with local id 1Nn8eD-0001vk-Vg for pgsql-sql@postgresql.org; Thu, 04 Mar 2010 10:51:17 +0000 To: pgsql-sql@postgresql.org Subject: Deleting rows from a table not contained in another table From: Florian Weimer Date: Thu, 04 Mar 2010 10:51:17 +0000 Message-ID: <82eik04axm.fsf@mid.bfk.de> MIME-Version: 1.0 Content-Type: text/plain; charset=iso-8859-1 Content-Transfer-Encoding: quoted-printable X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.555 tagged_above=-10 required=5 tests=AWL=0.044, BAYES_00=-2.599 X-Spam-Level: X-Archive-Number: 201003/28 X-Sequence-Number: 33735 I want to reimplement DELETE FROM foo; INSERT INTO foo SELECT * FROM bar; in a way which does not touch rows which are not modified (mainly to avoid locking issues). I've come up with this: DELETE FROM foo WHERE NOT EXISTS (SELECT * FROM bar WHERE foo.* IS NOT DISTINCT FROM bar.*); INSERT INTO foo SELECT * FROM bar EXCEPT SELECT * FROM foo; The problem is that the plan for the DELETE doesn't look pretty at all: QUERY PLAN ----------------------------------------------------------------------- Nested Loop Anti Join (cost=3D313.36..181568.96 rows=3D1 width=3D6) Join Filter: (NOT (foo.* IS DISTINCT FROM bar.*)) -> Seq Scan on foo (cost=3D0.00..293.05 rows=3D20305 width=3D38) -> Materialize (cost=3D313.36..516.40 rows=3D20305 width=3D32) -> Seq Scan on bar (cost=3D0.00..293.05 rows=3D20305 width=3D32) (5 rows) Is there some way to turn this into a merge join, short of introducing primary keys and using them to guide the join operation? --=20 Florian Weimer BFK edv-consulting GmbH http://www.bfk.de/ Kriegsstra=DFe 100 tel: +49-721-96201-1 D-76133 Karlsruhe fax: +49-721-96201-99