Delete duplicate rows, keeping the oldest

Sql

Uses a window function to number the duplicates and removes everything but the first of each group.

DELETE FROM contacts
WHERE id IN (
  SELECT id FROM (
    SELECT id,
           ROW_NUMBER() OVER (PARTITION BY email ORDER BY id) AS rn
    FROM contacts
  ) ranked
  WHERE ranked.rn > 1
);

More in Databases

Random picks