WITH Syntax to Delete Duplicate Records with No Primary Key

If you are missing a primary key, here is a great way to delete duplicate records in an SQL table. This example uses WITH to create a temporary table and PARTITION BY for row count. Any row with a row count greater than one will be deleted.

WITH NumberedTable AS (
SELECT ROW_NUMBER() OVER(PARTITION BY RowOne, RowTwo, RowThree, RowFour
ORDER BY RowOne, RowTwo, RowThree,RowFour)
AS DuplicateNumber FROM dbo.Table
)
DELETE FROM NumberedTable WHERE DuplicateNumber > 1;

Leave a Reply