89

I have unique id and email fields. Emails get duplicated. I only want to keep one Email address of all the duplicates but with the latest id (the last inserted record).

How can I achieve this?

Alejandro
  • 7,290
  • 4
  • 34
  • 59
Khuram
  • 1,156
  • 2
  • 14
  • 16
  • 1
    Have you tried to search? possible duplicate [how-do-i-delete-duplicate-rows-and-keep-the-first-row](http://stackoverflow.com/questions/6103212/how-do-i-delete-duplicate-rows-and-keep-the-first-row) – sra May 24 '11 at 07:42
  • 1
    why don't you just prevent duplicates from being inserted into the table? make email a unique index – tofutim May 24 '11 at 07:44
  • @sra, buddy I got like 20 threads still open but not being a database pro, all of those have some conditions which make the query pretty hard to understand, hence I made a new thread with lots of apologies @tofutim: Tim, we got this data from a third party so cant choose much. Hence cleaning up now. :-) – Khuram May 24 '11 at 07:46

11 Answers11

177

Imagine your table test contains the following data:

  select id, email
    from test;

ID                     EMAIL                
---------------------- -------------------- 
1                      aaa                  
2                      bbb                  
3                      ccc                  
4                      bbb                  
5                      ddd                  
6                      eee                  
7                      aaa                  
8                      aaa                  
9                      eee 

So, we need to find all repeated emails and delete all of them, but the latest id.
In this case, aaa, bbb and eee are repeated, so we want to delete IDs 1, 7, 2 and 6.

To accomplish this, first we need to find all the repeated emails:

      select email 
        from test
       group by email
      having count(*) > 1;

EMAIL                
-------------------- 
aaa                  
bbb                  
eee  

Then, from this dataset, we need to find the latest id for each one of these repeated emails:

  select max(id) as lastId, email
    from test
   where email in (
              select email 
                from test
               group by email
              having count(*) > 1
       )
   group by email;

LASTID                 EMAIL                
---------------------- -------------------- 
8                      aaa                  
4                      bbb                  
9                      eee                                 

Finally we can now delete all of these emails with an Id smaller than LASTID. So the solution is:

delete test
  from test
 inner join (
  select max(id) as lastId, email
    from test
   where email in (
              select email 
                from test
               group by email
              having count(*) > 1
       )
   group by email
) duplic on duplic.email = test.email
 where test.id < duplic.lastId;

I don't have mySql installed on this machine right now, but should work

Update

The above delete works, but I found a more optimized version:

 delete test
   from test
  inner join (
     select max(id) as lastId, email
       from test
      group by email
     having count(*) > 1) duplic on duplic.email = test.email
  where test.id < duplic.lastId;

You can see that it deletes the oldest duplicates, i.e. 1, 7, 2, 6:

select * from test;
+----+-------+
| id | email |
+----+-------+
|  3 | ccc   |
|  4 | bbb   |
|  5 | ddd   |
|  8 | aaa   |
|  9 | eee   |
+----+-------+

Another version, is the delete provived by Rene Limon

delete from test
 where id not in (
    select max(id)
      from test
     group by email)
Jose Rui Santos
  • 15,009
  • 9
  • 58
  • 71
  • Hi Jose, this is very educating. Thank you. However, MySQL threw an error. It has some syntax error near inner join (2nd line). Doesnt shed much light on the error though. – Khuram May 24 '11 at 10:38
  • @Khuram hold on for some hours, til I get home and check that on my machine – Jose Rui Santos May 24 '11 at 10:56
  • @Khuram I still cannot test it, but in the meanwhile I have updated the final delete statement. Try again please – Jose Rui Santos May 24 '11 at 11:35
  • @Jose This new query is processing. I got like 6,00,000 records so it might run till you get home. I will keep you posted. Cheers. – Khuram May 24 '11 at 12:06
  • Your optimized query is exactly what i had been looking for, otherwise it is insanely slow, though, i'm not sure if there is any scope for further improvement. – Fr0zenFyr Aug 30 '13 at 13:22
  • @Fr0zenFyr Most likely you need to create indexes to the columns that correspond to the `id` and `email` columns. If you already have those indexes created, make sure statistics are updated by running `ANALYZE TABLE`. You can run an `EXPLAIN SELECT` to inspect what is going wrong, see http://dev.mysql.com/doc/refman/5.0/en/using-explain.html – Jose Rui Santos Sep 08 '13 at 06:37
  • Thanks for the comment, I already have the indexes updated. Explain shows the use of `Using filesort` and `Using temporary` that causes some lag. I know that temporary table is used to store the result from subquery and filesort is used by group by. bah.. – Fr0zenFyr Sep 09 '13 at 04:29
  • That should work for a 'Select' statement also, correct? – Dror Jan 05 '17 at 09:42
  • @Dror Yes, that's correct. You can replace the `delete test` by `select *` to have a preview of what will be deleted. – Jose Rui Santos Jan 05 '17 at 11:54
  • 25
    Could be: `DELETE FROM test WHERE id NOT IN (SELECT MAX(id) FROM test GROUP BY email)` – Rene Limon Apr 26 '17 at 22:59
  • 5
    I get the error `Table 'test' is specified twice, both as a target for 'DELETE' and as a separate source for data` – Hamman Samuel Oct 02 '17 at 20:10
  • 13
    @HamSam Try to use a nested subquery so that mySql materializes it and no longer uses the "same table",e.g., use `delete from test where id not in ( SELECT * FROM (select max(id) from test group by email) AS S)` (I have added the uppercase part) – Jose Rui Santos Oct 03 '17 at 09:03
  • @JoseRuiSantos I want same solution but my table doesn't have primary (id) any suggestion would be appreciate Thanks :) – Ajay Korat Apr 26 '19 at 07:09
  • @Ajay Korat It doesn’t literally need to be an Id column. You need to replace ID by whatever your primary key is, which can be a column or a set of columns that unequivocally identify a single row. – Jose Rui Santos Apr 26 '19 at 19:12
59

Try this method

DELETE t1 FROM test t1, test t2 
WHERE t1.id > t2.id AND t1.email = t2.email
Suraj Rao
  • 29,388
  • 11
  • 94
  • 103
Pulkit Malhotra
  • 621
  • 6
  • 6
  • Create a table with 2 columns :- id (which is primary key and email which contain duplicates) and then run this query, you will get it. This is self join from the same table which is deleting duplicate records by keeping one copy – Pulkit Malhotra Aug 25 '18 at 10:39
  • 4
    Not sure why this is hiding so far down the page. Simple and effective – slightlyfaulty Jul 09 '20 at 19:50
  • 2
    Does this really keep the latest? The latest has the highest `id`, and it looks like this query is deleting any `id` which is greater than other `id`s. See @TanvirChowdhury answer at https://stackoverflow.com/a/63434018/277267 – Daniel F Mar 29 '21 at 08:27
  • 1
    just need to swap to t2.id > t1.id to keep the bigger one (t2) – Hoang Tran Jun 25 '22 at 04:22
  • 2
    Make sure that you have your columns indexed (id and mainly email in that example). Otherwise it will take several minutes (or hours) if you have thousands or millions of registers. – Luis Rodriguez Jan 23 '23 at 20:19
  • this would keep the smallest id ? `where t1.id < t2.id` would keep the last entry ? Thanks for sharing the trick :) – Antony Gibbs Apr 07 '23 at 01:30
19

Correct way is

DELETE FROM `tablename`
  WHERE `id` NOT IN (
    SELECT * FROM (
      SELECT MAX(`id`) FROM `tablename`
        GROUP BY `name`
    ) 
  )
Gaurav Kandpal
  • 1,250
  • 2
  • 15
  • 33
  • What's the purpose of the x character? – Codex73 Feb 15 '19 at 15:12
  • 4
    Results in ERROR 1248 (42000): Every derived table must have its own alias, adding as alias called DTAB works as shown here: DELETE FROM `tablename` WHERE id NOT IN (SELECT * FROM (SELECT MAX(id) FROM tablename GROUP BY name) as DTAB) – Mr Ed Jun 05 '20 at 10:43
  • 1
    To resolve the error 1248, I had to add `AS x` after the first closed parenthesis after the `GROUP BY` variable; line 6 in the answer. – Alex P. Miller Dec 15 '22 at 00:23
6

If you want to keep the row with the lowest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id > n2.id AND n1.email = n2.email

If you want to keep the row with the highest id value:

DELETE n1 FROM 'yourTableName' n1, 'yourTableName' n2 WHERE n1.id < n2.id AND n1.email = n2.email

or this query might also help

DELETE FROM `yourTableName` 
  WHERE id NOT IN (
    SELECT * FROM (
      SELECT MAX(id) FROM yourTableName 
        GROUP BY name
    ) 
  )
TanvirChowdhury
  • 2,498
  • 23
  • 28
4
DELETE 
FROM
  `tbl_job_title` 
WHERE id NOT IN 
  (SELECT 
    * 
  FROM
    (SELECT 
      MAX(id) 
    FROM
      `tbl_job_title` 
    GROUP BY NAME) tbl)

revised and working version!!! thank you @Gaurav

Gobinda Nandi
  • 457
  • 7
  • 18
2

I personally had trouble with the top two voted answers. It's not the cleanest solution but you can utilize temporary tables to avoid all the issues MySQL has with deleting via joining on the same table.

CREATE TEMPORARY TABLE deleteRows;
SELECT MIN(id) as id FROM myTable GROUP BY myTable.email;

DELETE FROM myTable
WHERE id NOT IN (SELECT id FROM deleteRows);
Jeff Fol
  • 1,400
  • 3
  • 18
  • 35
1

I must say that the optimized version is one sweet, elegant piece of code, and it works like a charm even when the comparison is performed on a DATETIME column. This is what I used in my script, where I was searching for the latest contract end date for each EmployeeID:

DELETE CurrentContractData
  FROM CurrentContractData
  INNER JOIN (
    SELECT
      EmployeeID,
      PeriodofPerformanceStartDate,
      max(PeriodofPerformanceEndDate) as lastDate,
      ContractID
    FROM CurrentContractData
    GROUP BY EmployeeID
    HAVING COUNT(*) > 1) Duplicate on Duplicate.EmployeeID = CurrentContractData.EmployeeID
    WHERE CurrentContractData.PeriodofPerformanceEndDate < Duplicate.lastDate;

Many thanks!

Michael Sheaver
  • 2,059
  • 5
  • 25
  • 38
  • I hat a similar issue, and tried you rebuild your query to my tables. I noticed `DELETE nytable FROM mytable .....` die not work, Si I changed the first 2 lines to `DELETE from mytable WHERE id IN (SELECT id FROM mytable ....`. – Radon8472 Jul 08 '22 at 10:02
0
DELIMITER // 
CREATE FUNCTION findColumnNames(tableName VARCHAR(255))
RETURNS TEXT
BEGIN
    SET @colNames = "";
     SELECT GROUP_CONCAT(COLUMN_NAME) FROM INFORMATION_SCHEMA.columns
        WHERE TABLE_NAME = tableName
        GROUP BY TABLE_NAME INTO @colNames;
    RETURN @colNames;
END // 
DELIMITER ;

DELIMITER // 
CREATE PROCEDURE deleteDuplicateRecords (IN tableName VARCHAR(255))
BEGIN
    SET @colNames = findColumnNames(tableName);
    SET @addIDStmt = CONCAT("ALTER TABLE ",tableName," ADD COLUMN id INT AUTO_INCREMENT KEY;");
    SET @deleteDupsStmt = CONCAT("DELETE FROM ",tableName," WHERE id NOT IN 
        ( SELECT * FROM ",
            " (SELECT min(id) FROM ",tableName," group by ",findColumnNames(tableName),") AS tmpTable);");
    set @dropIDStmt = CONCAT("ALTER TABLE ",tableName," DROP COLUMN id");

    PREPARE addIDStmt FROM @addIDStmt;
    EXECUTE addIDStmt;

    PREPARE deleteDupsStmt FROM @deleteDupsStmt;
    EXECUTE deleteDupsStmt;

    PREPARE dropIDStmt FROM @dropIDStmt;
    EXECUTE dropIDstmt;

END // 
DELIMITER ;

Nice stored procedure I created for deleting all duplicate records of a table without needing an existing unique id on that table.

CALL deleteDuplicateRecords("yourTableName");
TheAppFoundry
  • 93
  • 1
  • 9
0

I want to remove duplicate records based on multiple columns in table, so this approach worked for me,

Step 1 - Get max id or unique id from duplocate records

select *  FROM ( SELECT MAX(id) FROM table_name 
group by travel_intimation_id,approved_by,approval_type,approval_status having 
count(*) > 1

Step 2 - Get ids of single records from table

select *  FROM ( SELECT id FROM table_name 
group by travel_intimation_id,approved_by,approval_type,approval_status having 
count(*) = 1

Step 3 - Exclude above 2 queries from delete to

DELETE FROM `table_name` 
WHERE 
id NOT IN (paste step 1 query) a //to exclude duplicate records
and 
id NOT IN (paste step 2 query) b // to exclude single records

Final Query :-

DELETE FROM `table_name` 

WHERE id NOT IN (

select *  FROM ( SELECT MAX(id) FROM table_name 
group by travel_intimation_id,approved_by,approval_type,approval_status having 
count(*) > 1) a 
)
and id not in (

select *  FROM ( SELECT id FROM table_name 
group by travel_intimation_id,approved_by,approval_type,approval_status having 
count(*) = 1) b
);

By this query only duplocate records will delete.

Pooja Choudhary
  • 160
  • 1
  • 2
  • 14
0

Please try the following solution (based on the comments of the '@Jose Rui Santos' answer):

-- Set safe mode to false since;
-- You are using safe update mode and tried to update a table without a WHERE that uses a KEY column
SET SQL_SAFE_UPDATES = 0;

-- Delete the duplicate rows based on the field_with_duplicate_values 
-- Keep the unique rows with the highest id
DELETE FROM table_to_deduplicate
WHERE id NOT IN (
    SELECT * FROM (
        -- Select the highest id grouped by the field_with_duplicate_values
        SELECT MAX(id)
        FROM table_to_deduplicate
        GROUP BY field_with_duplicate_values
    )
    -- Subquery and alias needed since;
    -- You can't specify target table 'table_to_deduplicate' for update in FROM clause
    AS table_sub
);

-- Set safe mode to true
SET SQL_SAFE_UPDATES = 1;
Wouter Vanherck
  • 2,070
  • 3
  • 27
  • 41
0
delete  from iamsmsaccountmetadata where 
 id not in (select del.id from ( select iid,max(id) as id
 from iam.iamsmsaccountmetadata
 group by iid
 having count(*) > 1) as del )

This is the exact way Tried and Tested

Fedor
  • 17,146
  • 13
  • 40
  • 131