Delete Statement: Why is this better?

  • Good day Forum.

    In the app I'm working on I have seen the following delete statement:

    DELETE from tblFOO where fooKey IN

    (

    Select F.fooKey from tblFoo F inner join tblBar B

    ON F.abc = B.abc

    inner join tblBaz B2 ON B.abc = B2.abc

    inner join tblGamma G ON B2.abc = G.abc

    WHERE (list of conditions)

    )

    I thought this would be less optimal than the following:

    DELETE F FROM

    tblFoo F inner join tblBar B ON F.abc = B.abc

    inner join tblBaz B2 ON B.abc = B2.abc

    inner join tblGamma G ON B2.abc = G.abc

    WHERE (list of conditions)

    So I plugged both into query analyzer and the first one evaluates to 40 %, the second to 60%.

    Why would this be?

    Thanks

  • The second query may produce a lot of duplicate rows in tblFOO.

    Also, joins in subqueries always seem to be done with nested loops which is rarely efficient.

    (Derived tables are fine.)

    If you want to do a ANSI delete you should try nested EXISTS statements.

    eg.

    DELETE tblFOO

    WHERE fooKey IN

    (

    &nbsp&nbsp&nbsp&nbspSELECT F.fooKey

    &nbsp&nbsp&nbsp&nbspFROM tblFoo F

    &nbsp&nbsp&nbsp&nbspWHERE EXISTS

    &nbsp&nbsp&nbsp&nbsp(

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspSELECT *

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFROM tblBar B

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspWHERE F.abc = B.abc

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspAND EXISTS

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp(

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspSELECT *

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspFROM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&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspAND (B2 where conditions)

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp)

    &nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbsp&nbspAND (B where conditions)

    &nbsp&nbsp&nbsp&nbsp)

    &nbsp&nbsp&nbsp&nbspAND (F where conditions)

    )

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply