← All Exercises

Delete Duplicate Customers Keeping the Newest Row

intermediatesql~20min

Background

Imports and retries often insert the same customer twice. Deduplication must be deterministic, auditable, and safe to rerun on production data.

Problem

A customers table contains repeated email addresses with different update timestamps. Delete duplicate rows so one row per email remains, keeping the most recent updated_at and breaking ties with the highest id.

Input

A PostgreSQL customers table with id bigint GENERATED ALWAYS AS IDENTITY PRIMARY KEY, email text NOT NULL, and updated_at timestamptz NOT NULL.

Output

The DELETE removes only duplicate rows; the table keeps one row per case-insensitive email, choosing the greatest updated_at and then the greatest id.

Sample tests

Sample 1

Input: ids 1 [email protected] 2026-01-01; 2 [email protected] 2026-03-01; 3 [email protected] 2026-02-01; 4 [email protected] 2026-02-01; 5 [email protected] 2026-04-01
Expected: remaining ids: 2, 4, 5
deleted ids: 1, 3

Sample 2

Input: ids 1 through 5 with five distinct email addresses
Expected: remaining ids: 1, 2, 3, 4, 5
deleted ids: none

Your solution

Learning objective

Combine window ranking with a data-modifying CTE, normalize comparison keys, and define deterministic tie-break rules.