Removing duplicate rows from table in Oracle

前端 未结 22 1554
醉话见心
醉话见心 2020-11-22 12:57

I\'m testing something in Oracle and populated a table with some sample data, but in the process I accidentally loaded duplicate records, so now I can\'t create a primary ke

22条回答
  •  无人及你
    2020-11-22 13:15

    The Fastest way for really big tables

    1. Create exception table with structure below: exceptions_table

      ROW_ID ROWID
      OWNER VARCHAR2(30)
      TABLE_NAME VARCHAR2(30)
      CONSTRAINT VARCHAR2(30)
      
    2. Try create a unique constraint or primary key which will be violated by the duplicates. You will get an error message because you have duplicates. The exceptions table will contain the rowids for the duplicate rows.

      alter table add constraint
      unique --or primary key
      (dupfield1,dupfield2) exceptions into exceptions_table;
      
    3. Join your table with exceptions_table by rowid and delete dups

      delete original_dups where rowid in (select ROW_ID from exceptions_table);
      
    4. If the amount of rows to delete is big, then create a new table (with all grants and indexes) anti-joining with exceptions_table by rowid and rename the original table into original_dups table and rename new_table_with_no_dups into original table

      create table new_table_with_no_dups AS (
          select field1, field2 ........ 
          from original_dups t1
          where not exists ( select null from exceptions_table T2 where t1.rowid = t2.row_id )
      )
      

提交回复
热议问题