How to delete duplicate rows from a table?


Choose one of the following queries to delete duplicate rows from a table leaving only unique records in the table:

Method 1:

SQL> DELETE FROM table_name A WHERE ROWID > (
SQL>     SELECT min(rowid) FROM table_name B
SQL>     WHERE A.key_values = B.key_values);

Delete all rowids that is BIGGER than the SMALLEST rowid value (for a given key).

Method 2:

SQL> delete from my_table t1
SQL> where exists (select 'x' from my_table t2
SQL>                 where t2.key_value1 = t1.key_value1
SQL>                   and t2.key_value2 = t1.key_value2
SQL>                   and t2.rowid > t1.rowid);

Method 3:

SQL> delete from
SQL>   where rowid not in (select min(rowid)
SQL>                          from
SQL>                          group by columnA, columnB, columnC)

This query removes rows based on the column names specified in the GROUP BY clause. If you specify only one column name it will remove all duplicate records for that column. If you want to delete exact copy of the same row - use all the column names in the GROUP BY.


Comments