Choosing and reviewing the rows
WITH numbered AS (
SELECT id, email, name, updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id ASC
) AS rn
FROM contacts_dedup_demo
WHERE email IS NOT NULL
)
SELECT id, email, updated_at, rn
FROM numbered
WHERE rn > 1
ORDER BY email, id;Set up the example data
The table contains eight rows. Amy appears three times, Megan twice and Liam once. The two rows with no email are different contacts. We store fixed-width dates interpreted in the same way, so comparing the text is chronological for this data.
CREATE TABLE contacts_dedup_demo (
id INTEGER PRIMARY KEY,
email TEXT,
name TEXT NOT NULL,
updated_at TEXT NOT NULL
);
INSERT INTO contacts_dedup_demo VALUES
(1, 'amy@example.test', 'Previous Amy', '2026-09-01 10:00:00'),
(2, 'amy@example.test', 'Current Amy', '2026-09-03 12:00:00'),
(3, 'amy@example.test', 'Amy copy', '2026-09-03 12:00:00'),
(4, 'liam@example.test', 'Liam', '2026-09-02 09:00:00'),
(5, 'megan@example.test', 'Previous Megan', '2026-09-01 08:00:00'),
(6, 'megan@example.test', 'Current Megan', '2026-09-04 08:00:00'),
(7, NULL, 'Contact without email A', '2026-09-02 08:00:00'),
(8, NULL, 'Contact without email B', '2026-09-05 08:00:00');Download the full example (.sql)
The download uses an empty SQLite database with the same data and queries as this guide. Run it once on a test connection. The course's teaching editor has a limited engine, so run this script in SQLite rather than in the course lab.
What is kept, and why DISTINCT is not enough
DISTINCT removes repeats from the result you are querying; it does not delete stored records. Also, two rows with the same email but different ids or names will still be different if you select all their columns.
Separating detection from deletion avoids a dangerous assumption: sharing an attribute does not automatically make two entities the same. A family may share an email address. This example explicitly uses the rule “one contact per known email address”; confirm that this rule is appropriate before applying it to your system.
The guide on finding duplicates with GROUP BY and HAVING helps you measure the problem. Here we take the next step: choose a whole row to keep, review the rows to delete and check the resulting table.
The clean-up contract
| Decision | Example rule |
|---|---|
| Identity | exact email, not NULL |
| Row kept | Most recent update date |
| Tie | lowest id |
| Scope | Only contacts with known email |
| Relationships | The demo table has no child rows |
Step 1: review the three rows that would be deleted
ROW_NUMBER() starts at one within each email. The ordering puts the candidate we keep in first position. The id breaks the tie between rows 2 and 3; ordering by date alone would not decide which of them stays.
Checked candidates for deletion
| id | updated_at | rn | |
|---|---|---|---|
| 1 | amy@example.test | 2026-09-01 10:00:00 | 3 |
| 3 | amy@example.test | 2026-09-03 12:00:00 | 2 |
| 5 | megan@example.test | 2026-09-01 08:00:00 | 2 |
The outer query filters on the number calculated in the CTE. Do not put ROW_NUMBER() directly in WHERE. And do not use RANK() ordered by date alone if you need a single row to survive: the two tied contacts could get the same rank.
If the priority were «keep the verified record» or «keep the one with the most fields filled in», that criterion must come before the date in the ORDER BY. The example does not merge fields: it keeps one row exactly as it was. Choosing the most recent one may lose a phone number that only exists in an older copy; combining them needs a different operation.
Rehearsing the delete
Step 2: rehearse the DELETE inside a transaction
The preview above is for information only. For the rehearsal, open the transaction and run it again before the DELETE. In SQLite, BEGIN IMMEDIATE starts a write transaction and can fail if another connection holds an incompatible lock. Check that result; do not assume the transaction started.
BEGIN IMMEDIATE;Run the candidates SELECT again. Then delete by id, a non-null primary key; the email defines the groups, but the id identifies each row to delete.
WITH numbered AS (
SELECT id, email, name, updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id ASC
) AS rn
FROM contacts_dedup_demo
WHERE email IS NOT NULL
)
DELETE FROM contacts_dedup_demo
WHERE id IN (SELECT id FROM numbered WHERE rn > 1);The CTE is calculated again for this statement: it is not a stored list of candidates. In a real process, if you need sign-off on a frozen set, save the reviewed ids and their link to the row being kept in a work table, and check that the rows have not changed. Each engine's isolation level and locking also matter.
Step 3: check the rows kept and undo the rehearsal
SELECT email, COUNT(*) AS occurrences
FROM contacts_dedup_demo
WHERE email IS NOT NULL
GROUP BY email
HAVING COUNT(*) > 1;The query returns zero rows. That checks the uniqueness rule; it does not prove you kept the right data. Check the ids and names too:
SELECT id, email, name
FROM contacts_dedup_demo
ORDER BY id;The table during the rehearsal, after the DELETE
| id | name | |
|---|---|---|
| 2 | amy@example.test | Current Amy |
| 4 | liam@example.test | Liam |
| 6 | megan@example.test | Current Megan |
| 7 | NULL | Contact without email A |
| 8 | NULL | Contact without email B |
ROLLBACK;
SELECT COUNT(*) AS restored_rows
FROM contacts_dedup_demo;The count is back to 8. The download ends with ROLLBACK. In a clean-up you decide to commit, COMMIT replaces ROLLBACK at the end of that transaction, after you have reviewed the results. Do not run both expecting to commit something that has already been undone.
Dependencies and prevention
Before using it with related tables
If orders or other tables reference the duplicate ids, a DELETE can fail because of a foreign key, or remove child rows through a cascade. A duplicate contact and its orders are not necessarily disposable data. First build a «deleted id → kept id» map and decide how to move each relationship across.
Reassigning child rows can also cause conflicts with composite keys or UNIQUE constraints. For example, two merged profiles might have the same subscription. That collision needs a reconciliation rule; turning off foreign keys does not solve it. The standalone table in this guide teaches the ranking-and-delete pattern, not a full migration of entities.
What counts as the same email must also be defined. Case, spaces and collation can change which values the engine groups together. Do not normalise every email with LOWER and TRIM without first deciding the identity contract. If the application uses a normalised key, group by and protect that same key.
Adapting the delete to your engine
Ranking with ROW_NUMBER and an outer filter works in PostgreSQL, SQL Server, MySQL 8.0+ and SQLite 3.25+. The DELETE and the way you start a transaction differ. On databases with proper date/time types, use that type for updated_at instead of copying the demo's TEXT without thinking.
PostgreSQL: DELETE USING
WITH numbered AS (
SELECT id, email, name, updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id ASC
) AS rn
FROM contacts_dedup_demo
WHERE email IS NOT NULL
)
DELETE FROM contacts_dedup_demo AS c
USING numbered AS n
WHERE c.id = n.id AND n.rn > 1;USING joins the candidates to the table being deleted from. Start the process with BEGIN, and use COMMIT or ROLLBACK depending on the outcome of your review. Check isolation and concurrency for your real workload.
SQL Server: updatable CTE
;WITH numbered AS (
SELECT id, email, name, updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id ASC
) AS rn
FROM contacts_dedup_demo
WHERE email IS NOT NULL
)
DELETE FROM numbered
WHERE rn > 1;This CTE comes from a single table. The leading semicolon terminates any previous statement. The transaction is opened with BEGIN TRANSACTION; there is no BEGIN IMMEDIATE in T-SQL. Do not stretch direct deletion to a CTE with joins or aggregates that is not updatable.
MySQL: do not copy DELETE from another dialect
In MySQL 8.0+ you can rank with ROW_NUMBER, but there are restrictions on reading from the same table you are modifying. One explicit solution is to store the reviewed ids in a temporary work table and use a DELETE with a JOIN. Check the materialisation, the transactional engine (for example InnoDB) and the relationships. The SQLite syntax is not presented here as a tested recipe for MySQL.
Stopping them from coming back
Once the clean-up is committed, protect identity in the database. For this contract in SQLite, the following index stops a known email from repeating and allows several NULLs:
CREATE UNIQUE INDEX ux_contacts_dedup_email
ON contacts_dedup_demo(email);Do not create it after the rehearsal's ROLLBACK: Amy and Megan are duplicated again and creating it will fail. Apply the clean-up and the index as part of a controlled operation before reopening writes. Other engines have different rules for NULL in unique constraints; check UNIQUE before carrying the design over.
For large tables, review the plan, the log volume, the locks and the indexes that support the ranking. Deleting in batches keeps each transaction smaller, but you need to keep the candidate set and the survival rule stable. There is no universally optimal batch size.
Check another rule
WITH numbered AS (
SELECT id, email, name, updated_at,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY id ASC
) AS rn
FROM contacts_dedup_demo
WHERE email IS NOT NULL
)
SELECT id, email, rn
FROM numbered
WHERE rn = 1
ORDER BY id;The ids are 1, 4 and 5. By changing the ORDER BY you have changed the business decision, not just how the result looks. To list every row kept, you would also need ids 7 and 8, which this CTE deliberately leaves out.