Delete All Duplicates From Table

Mitch McConnell 41 Reputation points
2022-01-03T14:46:10.797+00:00

I am trying to write a stored procedure that will delete all duplicate orders from my table. I have the below query, but if an entry exists more than 2 times I have to run the process again. How can I delete all duplicates with one run of the stored procedure?

Delete
From [Orders]
Where Id In
(
Select Max(id)
from [Orders]
Group By OrderNumber
Having Count(id) > 1
)

Developer technologies Transact-SQL
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Olaf Helper 47,436 Reputation points
    2022-01-03T14:54:14.88+00:00

    Turn the logic around, use NOT IN and MIN function for those that shouldn't be deleted

    Delete
    From [Orders]
    Where NOT Id In
    (
    Select MIN(id)
    from [Orders]
    Group By OrderNumber
    Having Count(id) > 1
    )
    

  2. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2022-01-03T22:38:48.013+00:00

    If you want to delete all rows for a duplicate order number, you original query was pretty close:

    Delete
    From [Orders]
    Where OrderNumber In
    (
    Select OrderNumber
    from [Orders]
    Group By OrderNumber
    Having Count(id) > 1
    )
    

    If you want to keep one row per order number, the normal way to do it is

    ; WITH numbering AS (
        SELECT rowno = row_number() OVER(PARTITION BY OrderNumber ORDER BY <yourchoicehere>)
       FROM  Orders
    )
    DELETE numbering 
    WHERE rowno > 1
    
    0 comments No comments

  3. LiHong-MSFT 10,056 Reputation points
    2022-01-04T08:03:53.273+00:00

    Hi,@Mitch McConnell
    Please also check this:

    DELETE O   
    FROM  Orders O  
          INNER JOIN (SELECT *,RANK() OVER(PARTITION BY ID ORDER BY <primary key>) rank  
                      FROM #Person) T   
          ON O.OrderNumber  = T.OrderNumber   
    WHERE rank > 1;  
    

    Best regards,
    LiHong


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.