Find and safely delete duplicate records keeping the latest
Given users(id, email, created_at), write a query to find duplicate emails and delete older duplicates keeping only the newest row.
Model Answer & Explanation
WITH ranked AS (
SELECT id,
ROW_NUMBER() OVER (
PARTITION BY lower(email) ORDER BY created_at DESC, id DESC
) AS rn
FROM users
)
DELETE FROM users
WHERE id IN (SELECT id FROM ranked WHERE rn > 1); Rank rows per email by created_at DESC, id DESC with ROW_NUMBER() and delete where rn > 1 (or use Postgres ctid/id self-join). Always preview with SELECT first, wrap in a transaction, and add a UNIQUE index afterward so duplicates cannot recur.