sqlsqlcommand

How to remove duplicate rows with the same column in SQL


I have the following table in SQL:

enter image description here

I want to remove rows with the same id value.

Which query in SQL should I use?

The table should be as follows after the delete operation:

enter image description here


Solution

  • You could select all unique ids by using group by:

    Select 
       max(a)
       ,id
       from Table
       group by id
    

    If the above result is the result that you want to keep in your table then you could just do that:

    delete FROM Table
      where a not in (
        Select max(a)  from Table
        group by id
      )