Home » SQL & PL/SQL » SQL & PL/SQL » How to delete duplicate rows from a table?
How to delete duplicate rows from a table? [message #8853] Tue, 30 September 2003 06:31 Go to next message
charan
Messages: 5
Registered: August 2002
Junior Member
How to delete duplicate records from a table ??
Re: How to delete duplicate rows from a table? [message #8854 is a reply to message #8853] Tue, 30 September 2003 06:40 Go to previous messageGo to next message
Mahesh Rajendran
Messages: 10707
Registered: March 2002
Location: oracleDocoVille
Senior Member
Account Moderator
quoting orafaq
How does one eliminate duplicates rows from a table?
Choose one of the following queries to identify or remove duplicate rows from a table leaving only unique records in the table:
Method 1: 

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

Method 2: 
   SQL> create table table_name2 as select distinct * from table_name1;
   SQL> drop table_name1;
   SQL> rename table_name2 to table_name1;
   SQL> -- Remember to recreate all indexes, constraints, triggers, etc on table... 

Method 3: (thanks to Dennis Gurnick) 
   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);

Note: One can eliminate N^2 unnecessary operations by creating an index on the joined fields in the inner loop (no need to loop through the entire table on each pass by a record). This will speed-up the deletion process. 
Note 2: If you are comparing NOT-NULL columns, use the NVL function. Remember that NULL is not equal to NULL. This should not be a problem as all key columns should be NOT NULL by definition. 

Re: How to delete duplicate rows from a table? [message #8856 is a reply to message #8853] Tue, 30 September 2003 06:49 Go to previous messageGo to next message
hanuma
Messages: 5
Registered: June 2003
Junior Member
Delete from table
where rowid > ( select min(rowid)
from table
group by all_columns);

ok
Re: How to delete duplicate rows from a table? [message #8871 is a reply to message #8856] Tue, 30 September 2003 23:50 Go to previous message
rajesh
Messages: 173
Registered: November 1998
Senior Member
Small change is required in the above query ... as it deletes a row which is having only one row in the table
Delete from table
where rowid > ( select min(rowid)
from table
group by all_columns having count(*)>1);

Cheers
Rajesh
Previous Topic: Procedure for inserting vendors
Next Topic: ORA-01727: numeric precision specifier is out of range (1 to 38)
Goto Forum:
  


Current Time: Fri Apr 26 02:34:35 CDT 2024