Delete using JOIN vs using subquery performance

sakuraime 2,321 Reputation points
2021-05-31T11:02:41.857+00:00

there are two query for delete

delete from tableA a join tableb b on a.col1=b.col1

vs

delete from tableA a where col1 in (select col1 from tableb)

which one is performed faster. ?

SQL Server
SQL Server
A family of Microsoft relational database management and analysis systems for e-commerce, line-of-business, and data warehousing solutions.
12,759 questions
0 comments No comments
{count} votes

Accepted answer
  1. Erland Sommarskog 101.4K Reputation points MVP
    2021-05-31T21:52:06.183+00:00

    Short answer: it depends.

    Somewhat longer answer: for your actual case, you will need to benchmark.

    If I am to make a guess, I would guess that you get the same performance in most cases.

    0 comments No comments

2 additional answers

Sort by: Most helpful
  1. Olaf Helper 40,901 Reputation points
    2021-05-31T11:16:16.723+00:00

    which one is performed faster. ?

    Without knowing database/table design and existing indexes and data distribution no one can say.
    BTW, there is a a third-way with EXISTS, often fast:

    delete 
    from tableA a 
    where exists (select 1 from tableb as b where b.col1 = a.col1)
    
    2 people found this answer helpful.
    0 comments No comments

  2. Seeya Xi-MSFT 16,441 Reputation points
    2021-06-01T06:29:55.06+00:00

    Hi @sakuraime ,

    It can't say for certain. SQL isn’t just all about the time it takes to finish something, but it is about the sharing of resources as well.
    There is a third-way with EXISTS and the specific execution statement is as written by @Olaf Helper .
    The test results of the three methods are as follows:

    1. sub-select
      101219-t1.png
    2. exists
      101269-t2.png
    3. join
      101220-t3.png
      When rerunning the tests, you will get varying times as different things are running on your system.
      The key is to try different methods, and make sure you are picking the one that works best for your environment and situation.

    Best regards,
    Seeya


    If the response is helpful, please click "Accept Answer" and upvote it, as this could help other community members looking for similar queries.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments