Postgresql delete duplicate records

Common reason why we have to do this is there are times ( bad programming practice ) when you create a table with lots of data in it and forget to put unique constraints which takes system into bad state . Definitely bad programming practice but this happens sometimes .

       DELETE FROM dupes a
                           WHERE a.ctid <> (SELECT min(b.ctid)
                                     FROM   dupes b
                                     WHERE  a.key = b.key);

 

then the part remaining will be to create a unique constraint on the table.

  ALTER TABLE tablename ADD CONSTRAINT constraintname UNIQUE (columns);