Remove duplicate rows with a deliberate survivor rule
Deleting duplicates requires two decisions. Define which columns make two rows equivalent, then decide which physical row survives. A primary key distinguishes rows technically, but it is usually not part of the business definition of a duplicate.
Here a duplicate means the same person and channel. The lowest Id survives. This is an example policy, not a claim that the oldest identifier always contains the best data. If records carry different addresses, audit history or child references, resolve those differences before deleting anything.
Inspect the rule before applying it
The fixture has five rows. Ids 1 and 2 share Ada/north, and ids 4 and 5 share Lin/north. Id 3 is a separate Ada/south record. Ranking within (Person, Channel) gives the first member of each group number 1 and marks the surplus members with larger numbers.
Run one complete alternative in a fresh test connection without an existing transaction. Both use temporary data and roll back the demonstrated deletion. The preview must identify only ids 2 and 5 as surplus. The retained ids must be 1, 3 and 4.
Rehearse with SQL Server
Run this whole batch. The temporary table is local to this connection. The error handler rolls back the demonstration transaction if a statement fails.
CREATE TABLE #DuplicateDemo (
Id int PRIMARY KEY,
Person varchar(20) NOT NULL,
Channel varchar(20) NOT NULL
);
INSERT INTO #DuplicateDemo (Id, Person, Channel)
VALUES (1, 'Ada', 'north'), (2, 'Ada', 'north'),
(3, 'Ada', 'south'), (4, 'Lin', 'north'),
(5, 'Lin', 'north');
SELECT Id, Person, Channel,
ROW_NUMBER() OVER (
PARTITION BY Person, Channel ORDER BY Id
) AS PositionInGroup
FROM #DuplicateDemo
ORDER BY Id;
BEGIN TRY
BEGIN TRANSACTION;
WITH Ranked AS (
SELECT Id, ROW_NUMBER() OVER (
PARTITION BY Person, Channel ORDER BY Id
) AS PositionInGroup
FROM #DuplicateDemo
)
DELETE FROM Ranked WHERE PositionInGroup > 1;
SELECT Id, Person, Channel FROM #DuplicateDemo ORDER BY Id;
ROLLBACK TRANSACTION;
END TRY
BEGIN CATCH
IF XACT_STATE() <> 0 ROLLBACK TRANSACTION;
THROW;
END CATCH;
SELECT COUNT(*) AS RestoredRows FROM #DuplicateDemo;
DROP TABLE #DuplicateDemo;
The retained-row query returns three rows. RestoredRows is 5 because the example rolls back. SQL Server permits this single-table CTE to identify the rows deleted from its underlying table.
Rehearse with SQLite
Use a new in-memory connection, such as sqlite3 :memory:. SQLite applies the ranking in a subquery and deletes by the stable primary key.
CREATE TEMP TABLE DuplicateDemo (
Id INTEGER PRIMARY KEY,
Person TEXT NOT NULL,
Channel TEXT NOT NULL
);
INSERT INTO DuplicateDemo (Id, Person, Channel)
VALUES (1, 'Ada', 'north'), (2, 'Ada', 'north'),
(3, 'Ada', 'south'), (4, 'Lin', 'north'),
(5, 'Lin', 'north');
SELECT Id, Person, Channel,
ROW_NUMBER() OVER (
PARTITION BY Person, Channel ORDER BY Id
) AS PositionInGroup
FROM DuplicateDemo
ORDER BY Id;
BEGIN TRANSACTION;
DELETE FROM DuplicateDemo
WHERE Id IN (
SELECT Id FROM (
SELECT Id, ROW_NUMBER() OVER (
PARTITION BY Person, Channel ORDER BY Id
) AS PositionInGroup
FROM DuplicateDemo
) AS Ranked
WHERE PositionInGroup > 1
);
SELECT Id, Person, Channel FROM DuplicateDemo ORDER BY Id;
ROLLBACK;
SELECT COUNT(*) AS RestoredRows FROM DuplicateDemo;
DROP TABLE DuplicateDemo;
Expect retained ids 1, 3 and 4, followed by a restored count of 5. If an interactive statement fails, stop and roll back before continuing. Closing this isolated connection also discards its temporary fixture.
Separate ranking from data repair
ORDER BY Id is unique here, so survivor selection is deterministic. Ordering only by a timestamp that can tie leaves an unresolved choice. Add a stable unique tie-breaker after the actual business preference.
Grouping also depends on comparison rules. Case-insensitive collations can group differently cased text together, and NULLs can occupy the same partition. This fixture prohibits NULLs to keep that policy explicit. Decide how missing values and normalization should affect your real identity before selecting survivors.
A transaction is not a complete production migration plan. Concurrent writers may add duplicates after a preview, foreign keys may reference the proposed losers, and cascades can affect other tables. Reconcile references, choose an isolation strategy and verify affected counts as part of that separate change. Add an appropriate unique constraint only after confirming it expresses the intended future rule.
Source and further reading
This article addresses the problem raised by Alex in “Finding and deleting duplicate values in a SQL table” on Stack Overflow, licensed under CC BY-SA 4.0 . The question is the topic source. The explanations and examples here are newly authored from the database documentation, rather than reproduced from a community answer.


Author: Herman Schoenfeld