Say I have two tables:
create table parent (
number not null,
constraint parent_pk primary key(id),
)
create table child (
id number not null,
parent_id number not null,
constraint child_pk primary key(id),
constraint child_fk1 foreign key(parent_id)
references parent(id)
)
I’ve heard about bottom-up delete method. Something like this:
DELETE FROM child where parent_id IN (SELECT id FROM parent WHERE ...);
DELETE FROM parent WHERE ...;
I’ve also seen the following version:
DELETE FROM child c where exists (SELECT 1 FROM parent p WHERE c.parent_id=p.id AND ...);
DELETE FROM parent WHERE ...;
There are also exist ON DELETE CASCADE option. Could you please compare the performance of the mentioned ways?
As you are interested in the algorithm, what your question seems to boil down to is the difference between
INandEXISTSas your two examples are the same save for theINchanging to anEXISTSin the delete from theCHILDtable.There has been quite a lot written about this difference over the years but in essence
INis generally used where the number of comparators is small whereasEXISTSis more efficient for subqueries returning a larger number of comparators (especially if those values contain a large number of duplicates).INhas to evaluate every returned comparator whileEXISTSis satisfied when it encounters the first match.There are exceptions to this and if you google for them then you will find them but on the whole this seems to hold true.
Tom Kyte (Oracle VP) has a very good answer with explanations here:
http://asktom.oracle.com/pls/asktom/f?p=100:11:2148775836129778::::P11_QUESTION_ID:953229842074
TechRepublic also has a good explanation here:
http://www.techrepublic.com/article/oracle-tip-understand-the-difference-between-in-and-exists-in-subqueries/5297080
Hope this helps…