Deduplicate Rows Keeping the Latest
Remove duplicate natural keys and keep only the most recent row using a window function and a delete, a common cleanup before adding a unique constraint.
Code
DELETE FROM contacts
WHERE id IN (
SELECT id
FROM (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id DESC
) AS rank
FROM contacts
) ranked
WHERE rank > 1
);
-- After deduplication the unique constraint can be added safely:
ALTER TABLE contacts ADD CONSTRAINT contacts_email_key UNIQUE (email);How it works
Several statements share this file — SELECT / DELETE / ALTER, with contacts among the objects involved.
Breaking the statements into their working parts: a WHERE clause limiting the rows one statement is allowed to reach; a window function (OVER (…)) deriving values across rows while keeping every row distinct; an ORDER BY that fixes the output order; UNIQUE constraints that keep duplicate values out.
What to watch for
- Window functions are evaluated after
WHEREandGROUP BY— their output is not visible to a same-levelWHERE.
Applying it
Run the statement against the contacts table.
Statements that matter
DELETE FROM contacts
WHERE id IN (
SELECT id
FROM (
SELECT
id,
ROW_NUMBER() OVER (
PARTITION BY email
ORDER BY updated_at DESC, id DESC
) AS rank
FROM contacts
) ranked
WHERE rank > 1
);
ALTER TABLE contacts ADD CONSTRAINT contacts_email_key UNIQUE (email);
Interactive Tools for This Topic
PostgreSQL EXPLAIN AnalyzerAnalyze PostgreSQL EXPLAIN ANALYZE text or FORMAT JSON plans locally to flag Seq Scans, slow nodes, row misestimates, disk sorts, and index hints.SQL DDL to TypeScript ConverterConvert SQL CREATE TABLE DDL statements into strict TypeScript interfaces with nullable, array, enum, JSONB, and Date or ISO string column mappings.Duplicate Line RemoverFind unique, duplicate, or counted lines with optional case sensitivity and whitespace trimming, all processed locally in the browser.Multi-Mode Escape & Unescape CodecEscape and unescape strings safely across JSON, JavaScript, SQL single-quoted literals, POSIX shell single quotes, and RFC 4180 CSV cells in your browser.
FAQ
- Name the tables involved in this file.
- `contacts` — referenced directly, no join needed.
Report a problem with this exampleOpens a pre-filled issue on GitHub.