Re: DELETE FROM t WHERE EXISTS - Mailing list pgsql-sql

From Jeff Eckermann
Subject Re: DELETE FROM t WHERE EXISTS
Date
Msg-id 20030228193056.21775.qmail@web20805.mail.yahoo.com
Whole thread Raw
In response to DELETE FROM t WHERE EXISTS  ("Dan Langille" <dan@langille.org>)
List pgsql-sql
--- Dan Langille <dan@langille.org> 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/


pgsql-sql by date:

Previous
From: Jakub Ouhrabka
Date:
Subject: Re: DELETE FROM t WHERE EXISTS
Next
From: Tom Lane
Date:
Subject: Re: DELETE FROM t WHERE EXISTS