The goal
A table has rows that should be unique but aren't. Maybe the same customer was loaded twice, or a job re-ran without an idempotency check. You want to see exactly which rows are duplicated, decide which copy to keep, remove the others safely and stop it happening again.
A common table expression (CTE) with ROW_NUMBER() does all of that in one readable pattern. The examples below use this table:
CREATE TABLE dbo.Customer (
CustomerID int IDENTITY(1,1) PRIMARY KEY,
Email nvarchar(256) NOT NULL,
FullName nvarchar(200) NOT NULL,
City nvarchar(100) NULL,
CreatedAt datetime2(0) NOT NULL DEFAULT SYSUTCDATETIME()
);
Here "duplicate" means two or more rows with the same Email. CustomerID is different on every row, so it is not part of the duplicate check.
Tip
Agree on the business definition of a duplicate before you write any SQL. "Same email" and "same email, name and city" give very different row counts.
Step 1: Count the duplicate groups
Start with a plain GROUP BY to see how big the problem is:
SELECT Email, COUNT(*) AS Copies
FROM dbo.Customer
GROUP BY Email
HAVING COUNT(*) > 1
ORDER BY Copies DESC;
This tells you which keys are duplicated and how many times. It does not show the individual rows, and you cannot delete with it. That is what the CTE is for.
Step 2: Number the rows in each group with a CTE
ROW_NUMBER() restarts at 1 for each PARTITION BY group. The ORDER BY inside OVER() decides which row gets number 1, which is the row you keep.
WITH Numbered AS (
SELECT CustomerID, Email, FullName, City, CreatedAt,
ROW_NUMBER() OVER (
PARTITION BY Email
ORDER BY CreatedAt ASC, CustomerID ASC
) AS rn
FROM dbo.Customer
)
SELECT *
FROM Numbered
WHERE rn > 1
ORDER BY Email, rn;
rn = 1is the oldest row for each email, so it is the one you keep.rn > 1lists every extra copy.CustomerIDcomes second in theORDER BYas a tie-breaker. Without it, two rows with the sameCreatedAtcan be numbered in a different order each time you run the query, and a delete could remove a different row from the one you reviewed.
To keep the newest row instead, use ORDER BY CreatedAt DESC, CustomerID DESC.
See each duplicate group in full
During review it helps to see the kept row next to its copies. COUNT(*) OVER adds the group size to every row:
WITH Grouped AS (
SELECT *,
COUNT(*) OVER (PARTITION BY Email) AS Copies,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, CustomerID) AS rn
FROM dbo.Customer
)
SELECT *
FROM Grouped
WHERE Copies > 1
ORDER BY Email, rn;
Exact duplicates with no key column
If the table has no unique column and the rows are identical in every column, partition by all the columns. Because the rows are identical, it doesn't matter which one is kept, so ORDER BY (SELECT NULL) is fine here:
WITH Numbered AS (
SELECT *,
ROW_NUMBER() OVER (
PARTITION BY Email, FullName, City, CreatedAt
ORDER BY (SELECT NULL)
) AS rn
FROM dbo.StagingCustomer
)
SELECT * FROM Numbered WHERE rn > 1;
Watch out for case, spaces and NULLs
| Situation | What happens | What to do |
|---|---|---|
Bob@X.com vs bob@x.com | With a case-insensitive collation (the usual default) they are treated as equal | Check the column's collation; add COLLATE Latin1_General_CS_AS in PARTITION BY if case matters |
Trailing spaces, 'a@x.com ' | = comparisons and grouping ignore trailing spaces, so these already match | No change needed for trailing spaces; use TRIM() for leading spaces |
NULL in a partition column | PARTITION BY puts all NULLs in the same group | Filter them out with WHERE City IS NOT NULL if NULL shouldn't count as a match |
Look-alike values (gmail.com vs googlemail.com) | Not detected | Partition by a cleaned expression, for example LOWER(TRIM(Email)) |
Step 3: Back up the rows you are about to delete
Copy the extra rows to a separate table before you delete anything. If the business later says a copy held the correct data, you can restore it.
WITH Numbered AS (
SELECT *,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, CustomerID) AS rn
FROM dbo.Customer
)
SELECT *
INTO dbo.Customer_Duplicates_20261115
FROM Numbered
WHERE rn > 1;
SELECT COUNT(*) AS RowsToDelete FROM dbo.Customer_Duplicates_20261115;
Check that RowsToDelete equals the total of Copies - 1 from Step 1.
Warning
Check foreign keys before deleting. If other tables (orders, addresses) point at a duplicate
CustomerID, the delete fails on the constraint or, withON DELETE CASCADE, removes their child rows too. Move the child rows to the keptCustomerIDfirst.
Step 4: Delete the duplicates through the CTE
SQL Server lets you DELETE from a CTE that reads a single table. Deleting from the CTE deletes the matching rows in the table underneath:
BEGIN TRANSACTION;
WITH Numbered AS (
SELECT CustomerID,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, CustomerID) AS rn
FROM dbo.Customer
)
DELETE FROM Numbered
WHERE rn > 1;
SELECT @@ROWCOUNT AS RowsDeleted; -- compare with RowsToDelete from Step 3
-- If the count matches:
COMMIT TRANSACTION;
-- If it doesn't:
-- ROLLBACK TRANSACTION;
Large tables: delete in batches
A single delete of millions of rows makes the transaction log grow, holds locks for a long time and can escalate to a table lock. Delete a few thousand rows at a time instead:
DECLARE @batch int = 5000, @deleted int = 1;
WHILE @deleted > 0
BEGIN
WITH Numbered AS (
SELECT CustomerID,
ROW_NUMBER() OVER (PARTITION BY Email ORDER BY CreatedAt, CustomerID) AS rn
FROM dbo.Customer
)
DELETE TOP (@batch) FROM Numbered
WHERE rn > 1;
SET @deleted = @@ROWCOUNT;
END;
Each pass recalculates the row numbers, so the kept row (rn = 1) stays the same on every pass. With the FULL recovery model, keep log backups running during the cleanup so the log can be reused. An index on (Email, CreatedAt, CustomerID) makes each pass much cheaper than scanning the whole table every time.
Caution
Run the cleanup against a restored copy or a test environment first, and run it in production in a maintenance window. Keep the backup table from Step 3 until the business has signed off.
Step 5: Stop duplicates coming back
Cleaning the data only fixes it until the next bad load. Add a unique constraint so SQL Server rejects new duplicates:
CREATE UNIQUE NONCLUSTERED INDEX UX_Customer_Email
ON dbo.Customer (Email);
If the column allows NULLs and many rows can be NULL, a normal unique index allows only one NULL. A filtered unique index enforces uniqueness only for non-NULL values:
CREATE UNIQUE NONCLUSTERED INDEX UX_Customer_City_NotNull
ON dbo.Customer (City)
WHERE City IS NOT NULL;
The index fails to build if any duplicates are left, which also confirms the cleanup worked.
Also fix the load that created the duplicates:
- Change blind
INSERTstatements toINSERT ... WHERE NOT EXISTSorMERGEon the business key. - Remove duplicates in the staging table with the same
ROW_NUMBER()CTE before loading the target. - Make reruns idempotent, so that running a job twice gives the same result as running it once.
Quick reference
| Task | Pattern |
|---|---|
| Which keys are duplicated | GROUP BY key HAVING COUNT(*) > 1 |
| List the extra rows | CTE + ROW_NUMBER() OVER (PARTITION BY key ORDER BY keep_rule, id), WHERE rn > 1 |
| Show whole groups | COUNT(*) OVER (PARTITION BY key), WHERE Copies > 1 |
| Remove the extras | DELETE FROM cte WHERE rn > 1 inside a transaction |
| Large tables | DELETE TOP (n) from the CTE in a loop |
| Prevent duplicates | Unique index, filtered when NULLs are allowed |
Get the weekly HubDatAI email
One email a week with everything new: posts, learning sessions and videos. Free, no spam, unsubscribe in one click. What you get