Search code examples
mysqlsql-deletedelete-rowunique-constraint

How to delete all rows in a group except the newest one?


Say, I have a table similar to this:

CREATE TABLE `mytable` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `application_id` int(11) NOT NULL,
  `company_name` varchar(100) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB

I want to make application_id unique, but there're some duplicates in the table already. How can I group by application_id and remove all records per group, leaving just the one with the highest id?


Solution

  • delete from mytable
    where id not in 
    (
      select max(id)
      from mytable
      group by application_id
    )