Received: from maia.hub.org (unknown [200.46.204.183]) by mail.postgresql.org (Postfix) with ESMTP id B0CFE635C81 for ; Fri, 17 Jul 2009 12:14:37 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.183]) (amavisd-maia, port 10024) with ESMTP id 43213-02-2 for ; Fri, 17 Jul 2009 12:14:27 -0300 (ADT) X-Greylist: domain auto-whitelisted by SQLgrey-1.7.6 Received: from tomts20-srv.bellnexxia.net (tomts20.bellnexxia.net [209.226.175.74]) by mail.postgresql.org (Postfix) with ESMTP id CBF6A6321E5 for ; Fri, 17 Jul 2009 12:04:49 -0300 (ADT) Received: from toip7.srvr.bell.ca ([209.226.175.124]) by tomts20-srv.bellnexxia.net (InterMail vM.5.01.06.13 201-253-122-130-113-20050324) with ESMTP id <20090717150448.DMMZ6916.tomts20-srv.bellnexxia.net@toip7.srvr.bell.ca> for ; Fri, 17 Jul 2009 11:04:48 -0400 X-IronPort-Anti-Spam-Filtered: true X-IronPort-Anti-Spam-Result: Al8FAFcuYEpA51xt/2dsb2JhbACBUc9DgjSBWQU Received: from bas4-london14-1088904301.dsl.bell.ca (HELO t60p.bax.ca) ([64.231.92.109]) by toip7.srvr.bell.ca with ESMTP; 17 Jul 2009 11:07:17 -0400 Message-ID: <4A609310.4050003@sympatico.ca> Date: Fri, 17 Jul 2009 11:04:48 -0400 From: Frank Bax User-Agent: Thunderbird 2.0.0.19 (X11/20090301) MIME-Version: 1.0 To: pgsql-sql@postgresql.org Subject: Re: De-duplicating rows References: <87E8E647-4CAD-4491-B687-FA763E0EBE7E@thebuild.com> <4A60265D.1060905@archonet.com> In-Reply-To: <4A60265D.1060905@archonet.com> Content-Type: text/plain; charset=ISO-8859-1; format=flowed Content-Transfer-Encoding: 7bit X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=0 tagged_above=0 required=5 tests=none X-Spam-Level: X-Archive-Number: 200907/77 X-Sequence-Number: 32818 Richard Huxton wrote: > Christophe wrote: >> Now, since this database has been production since 7.2 days, cruft has >> crept in: in particular, there are duplicate email addresses, some >> with mismatched attributes. The policy decision by the client is that >> the correct row is the one with the earliest timestamp. > > Something like (untested): > > CREATE TEMPORARY TABLE earliest_duplicates AS > SELECT > email AS tgt_email, > min(create_date) AS tgt_date > FROM mytable > GROUP BY email > HAVING count(*) > 1; > > DELETE FROM mytable USING earliest duplicates > WHERE email=tgt_email AND create_date > tgt_date; If it is possible that two rows exist for the same email/date; then you will likely need to deal with these manually. If you rerun the above SELECT after running the delete you should identify these rows.