Delete statement with joins

  • Just wanted to make sure that if I did something like the following that I would only be deleting from the 'FROM' (or 'a') table and that it would not delete from the joined tables as well.

    DELETE a FROM ATable a

    INNER JOIN BTable b

    INNER JOIN CTable c

    WHERE b.Field = 'something'

    AND c.Field = 'something else'

  • A delete can only affect a single table. It will affect the table that's specified straight after the DELETE [FROM]. Any tables after the second FROM are just used to identify rows to be deleted.

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • What Gail has said is right, it would delete from only one table.

    Your statement is missing ON clauses, is this only a test statement you have posted?


    Bru Medishetty

    Blog -- LearnSQLWithBru

    Join on Facebook Page Facebook.comLearnSQLWithBru

    Twitter -- BruMedishetty

  • As Bru mentioned, you haven't joined TableA, so you might end up deleting everything in that table. Only one table is affected, but how it is affected depends on your query.

    Write this as a SELECT, double check the results, and then turn it into a DELETE.

  • I personally nest all update/delete statements to real data in transactions as well, just to be extra cautious.

    something like:

    BEGIN TRAN

    --Your Delete Statement

    ROLLBACK TRAN

    --COMMIT TRAN

    Seth Phelabaum


    Consistency is only a virtue if you're not a screwup. 😉

    Links: How to Post Sample Data[/url] :: Running Totals[/url] :: Tally Table[/url] :: Cross Tabs/Pivots[/url] :: String Concatenation[/url]

  • Steve Jones - Editor (11/30/2009)


    As Bru mentioned, you haven't joined TableA

    It is joined, just the ON clauses are missing

    DELETE FROM a -- table to be deleted from

    FROM ATable a -- join to other tables to filter

    INNER JOIN BTable b .....

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • Steve Jones - Editor (11/30/2009)


    Write this as a SELECT, double check the results, and then turn it into a DELETE.

    That's my best suggestion to a beginner and intermediate programmer. That one additional step is a way of checking / confirming what records your DELETE statement is going to delete.


    Bru Medishetty

    Blog -- LearnSQLWithBru

    Join on Facebook Page Facebook.comLearnSQLWithBru

    Twitter -- BruMedishetty

Viewing 7 posts - 1 through 6 (of 6 total)

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