X-Original-To: pgsql-sql@postgresql.org Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id 7079C47615D for ; Fri, 28 Feb 2003 16:57:35 -0500 (EST) Received: from postgresql.org ([64.49.215.8]) by localhost (postgresql.org [64.49.215.8:10024]) (amavisd-new) with SMTP id 36974-05 for ; Fri, 28 Feb 2003 16:57:24 -0500 (EST) Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (Postfix) with ESMTP id 7986347616F for ; Fri, 28 Feb 2003 15:34:46 -0500 (EST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id DE85FD60F; Fri, 28 Feb 2003 12:34:45 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id CC2C95C04; Fri, 28 Feb 2003 12:34:45 -0800 (PST) Date: Fri, 28 Feb 2003 12:34:45 -0800 (PST) From: Stephan Szabo To: Dan Langille Cc: Subject: Re: DELETE FROM t WHERE EXISTS In-Reply-To: <3E5F530B.1649.424D34C1@localhost> Message-ID: <20030228123036.L2988-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Virus-Scanned: by amavisd-new X-Archive-Number: 200302/622 X-Sequence-Number: 12020 On Fri, 28 Feb 2003, Dan Langille wrote: > Hi folks, > > I wanted to delete "old" rows from a table. These are the rows I > want to keep: > > SELECT * > FROM clp > ORDER BY commit_date > LIMIT 100 > > So I tried this: > > DELETE FROM clp > WHERE NOT EXISTS ( > SELECT * > FROM clp > ORDER BY commit_date > LIMIT 100); > > Uhh uhh, nothing deleted. I don't understand why. As long as the inner select returns at least 1 result NOT EXISTS is going to return false (you haven't correlated the two queries at all). > OK, I can do this instead: > > DELETE from clp > where commit_log_id NOT in ( > SELECT commit_log_id > FROM clp > ORDER BY commit_date > LIMIT 100); > > Can you think of a better way? Possibly something like: DELETE FROM clp WHERE NOT EXISTS ( select * from (select * from clp order by commit_date limit 100) tmp where tmp.commit_log_id = clp.commit_log_id ); But I haven't tried it for stupid errors, and am not sure that it'd end up being any better than NOT IN anyway.