wasAsked.

How do you delete duplicate records from a table?

Impetus · Role not specified · technical

Published

Year not specified · SQL

Community answers

Posted by wasAsked editorial collection

The standard approach is to number rows within each group of duplicates and delete all but one. 1. Using ROW_NUMBER in a CTE (SQL Server) WITH Duplicates AS ( SELECT Id, ROW_NUMBER() OVER (PARTITION BY Email, PhoneNumber ORDER BY Id) AS rn FROM Contacts ) DELETE FROM Duplicates WHERE rn > 1; - PARTITION BY lists the columns that define a duplicate. - ORDER BY chooses which row survives (smallest Id here). 2. Using a GROUP BY with MIN or MAX (works in most databases) DELETE FROM Contacts WHERE Id NOT IN ( SELECT MIN(Id) FROM Contacts GROUP BY Email, PhoneNumber ); Be careful with NOT IN if the subquery can return NULL; here MIN(Id) of a non-null key is safe. In MySQL you may need to wrap the subquery in a derived table because MySQL does not allow selecting from the table being deleted directly. 3. Self-join (common in MySQL) DELETE c1 FROM Contacts c1 JOIN Contacts c2 ON c1.Email = c2.Email AND c1.PhoneNumber = c2.PhoneNumber AND c1.Id > c2.Id; 4. Copy distinct rows to a new table (for large tables or no key) SELECT DISTINCT Email, PhoneNumber, Name INTO Contacts_Clean FROM Contacts; -- validate, then swap tables (rename), recreate indexes and constraints Production checklist - Preview first: run the SELECT version to see which rows would be deleted. - Use a transaction and verify @@ROWCOUNT before committing. - Back up the rows you are deleting (or the whole table). - Handle foreign keys: re-point child records to the surviving row before deleting duplicates. - Delete in batches for very large tables to avoid long locks and log growth. - Decide which record should survive (oldest, newest, most complete) with the business. Prevent recurrence - Add a unique constraint or unique index on the duplicate-defining columns. - Validate in the application, and use idempotency keys or upserts (MERGE, INSERT ... ON CONFLICT) for imports and retries.

Ravindra Wadile · · 0 likes

Sign in to add your answer

Related interview topics