Video in progress

Duplicate rows have appeared in a table. How do you find them, and how do you keep one and delete the rest?

I find them with GROUP BY ... HAVING count(*) > 1, and to delete I mark everything except the first in each group with ROW_NUMBER() OVER (PARTITION BY ...) and run a DELETE. At the end I add a unique constraint, otherwise they'll show up again tomorrow.

📖 Answer

Finding them:

SELECT email, count(*)
FROM subscribers
GROUP BY email
HAVING count(*) > 1;

Deleting: for each email we keep the one with the smallest id:

DELETE FROM subscribers s
USING (
    SELECT id,
           ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
    FROM subscribers
) d
WHERE s.id = d.id
  AND d.rn > 1;

ORDER BY decides which row stays: the oldest, the newest, or the most completely filled in. That's a business decision, so agree on it beforehand.

On prod I don't do this directly:

  1. First I use a SELECT to see how many rows will be deleted, and I move the doomed rows to a backup table.
  2. If other tables (FKs) reference the duplicate rows, I first repoint them to the row that stays.
  3. Then I add the constraint with CREATE UNIQUE INDEX CONCURRENTLY.

You also need to find where the duplicates came from: usually "check first, then write" code under parallel requests, or a button that was clicked twice.