The following is database administration tip #2 from "30 tips in 30 minutes," brought to you by the IOUG. Return
to the main page for more tips on this topic.
Define two SQL*Plus user variables. One is the table with duplicate data. The other are the key columns of the table:
define vtable = test
define vkeys = 'a, b'
You can also use the exceptions feature of the table constraint addition. Create an exception table with the Oracle supplied script named utlexcpt.sql in the $ORACLE_HOME/rdbms/admin directory. Then add a constraint using the user defined variables like this:
ALTER TABLE &vtable add (CONSTRAINT &vtable._pk PRIMARY KEY (&vkeys.) USING INDEX STORAGE (initial 5K) EXCEPTIONS INTO exceptions);
Duplicate rows in your table will have their rows inserted into EXCEPTIONS table, even though the constraint addition fails. To find the duplicate rows, join the table to the exception table like this:
Rem Find the duplicate rows with using exceptions SELECT &vtable..* FROM &vtable., exceptions WHERE &vtable..rowid = exceptions.row_id;
Delete rows from your table using the exceptions table and the user defined variables like this:
Rem Remove the duplicate rows with using exceptions DELETE FROM &vtable WHERE (&vkeys , rowid) IN (SELECT &vkeys , max(rowid) FROM &vtable WHERE rowid IN (SELECT &vtable..rowed FROM &vtable., exceptions WHERE &vtable..rowid = exceptions.row_id) GROUP BY &vkeys HAVING COUNT(*) > 1);
Get more tips in minutes! Return to the main page.
About the author: Kenny Smith has been working with Oracle technology on HP servers for over a decade. He specializes in Oracle database architecture, database administration and development. He has presented at numerous Oracle conferences on two continents. He has published many articles describing Oracle solutions and has co-authored "Oracle backup and recovery 101" from Oracle Press.
IOUG: Become a member of the IOUG to access the paper referenced here and a repository of technical content created for Oracle users by Oracle users.