X-Original-To: pgsql-sql@postgresql.org Received: from localhost (postgresql.org [64.49.215.8]) by postgresql.org (Postfix) with ESMTP id C6F5F47629D for ; Fri, 28 Feb 2003 16:09:14 -0500 (EST) Received: from postgresql.org ([64.49.215.8]) by localhost (postgresql.org [64.49.215.8:10024]) (amavisd-new) with SMTP id 28447-03 for ; Fri, 28 Feb 2003 16:09:02 -0500 (EST) Received: from web20805.mail.yahoo.com (web20805.mail.yahoo.com [216.136.226.194]) by postgresql.org (Postfix) with SMTP id 090FA474E42 for ; Fri, 28 Feb 2003 14:30:57 -0500 (EST) Message-ID: <20030228193056.21775.qmail@web20805.mail.yahoo.com> Received: from [208.13.35.65] by web20805.mail.yahoo.com via HTTP; Fri, 28 Feb 2003 11:30:56 PST Date: Fri, 28 Feb 2003 11:30:56 -0800 (PST) From: Jeff Eckermann Subject: Re: DELETE FROM t WHERE EXISTS To: Dan Langille , pgsql-sql@postgresql.org In-Reply-To: <3E5F530B.1649.424D34C1@localhost> MIME-Version: 1.0 Content-Type: text/plain; charset=us-ascii X-Virus-Scanned: by amavisd-new X-Archive-Number: 200302/620 X-Sequence-Number: 12018 --- 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. > Your WHERE clause will never evaluate to true in this case, because something will always be returned by the subselect. > 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? > -- AFAIK joins cannot be used with DELETEs (but see below), so you are stuck with a subselect. If you don't like the performance of the IN, you could do an EXISTS using a correlated subselect from a subselect, but that is ugly. Or you could do it in two steps: SELECT INTO TEMP sometable * FROM clp ORDER BY commit_date LIMIT 100; DELETE FROM clp WHERE commit_date = sometable.commit_date; That last must be converted into a join clause somehow, but right now I am too lazy to turn on logging to find out what :-) __________________________________________________ Do you Yahoo!? Yahoo! Tax Center - forms, calculators, tips, more http://taxes.yahoo.com/