Use ROW_NUMBER() to number rows within each group of duplicates, then delete every row numbered greater than 1. Example table CREATE TABLE Customers (Id INT IDENTITY PRIMARY KEY, Email NVARCHAR(200), Name NVARCHAR(100), CreatedAt DATETIME2); Delete duplicates by Email, keeping the earliest record WITH Ranked AS ( SELECT Id, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, Id) AS rn FROM Customers ) DELETE FROM Ranked WHERE rn > 1; How it works - PARTITION BY Email groups rows that are considered duplicates (use several columns if duplicates are defined by more than one: PARTITION BY FirstName, LastName, DateOfBirth). - ORDER BY decides which row to keep: here the oldest (rn = 1). Use ORDER BY CreatedAt DESC to keep the newest. - In SQL Server, deleting from the CTE deletes the underlying table rows, because the CTE references a single table. Preview before deleting (always a good practice) WITH Ranked AS ( SELECT *, ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, Id) AS rn FROM Customers ) SELECT * FROM Ranked WHERE rn > 1; Tables without a unique key The same CTE approach still works in SQL Server, because ROW_NUMBER distinguishes identical rows even when all columns match. Safety steps for production - Run inside a transaction and check the row count before committing: BEGIN TRAN; WITH ... DELETE ...; SELECT @@ROWCOUNT; -- verify, then COMMIT or ROLLBACK - Back up the affected rows first (SELECT INTO a backup table). - For very large tables, delete in batches (DELETE TOP (5000) ... in a loop) to limit locking and log growth. - Consider foreign keys: child rows may reference duplicates; update them to point to the kept row first. Prevent future duplicates Add a unique constraint or unique index once cleaned: CREATE UNIQUE INDEX UX_Customers_Email ON Customers(Email); Other dialects PostgreSQL does not allow DELETE from a CTE directly in the same way; use DELETE ... USING with a CTE or WHERE id IN (SELECT id FROM ranked WHERE rn > 1). MySQL 8 supports CTEs in a similar subquery form.
Ravindra Wadile · · 0 likes