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.

SqlData Integrity

Code

sqlsnippet
17 lines
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 WHERE and GROUP BY — their output is not visible to a same-level WHERE.

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

FAQ

Name the tables involved in this file.
`contacts` — referenced directly, no join needed.