7
5 ways to delete duplicate records Oracle Posted on January 29, 2013 by sqlandplsql In Oracle there are many ways to delete duplicate records. Note that below example are described to just explain the different possibilities. Consider the EMP table with below rows create table emp( EMPNNO integer, EMPNAME varchar2(20), SALARY number);

5 Ways to Delete Duplicate Records

Embed Size (px)

DESCRIPTION

de

Citation preview

5 ways to delete duplicate recordsOraclePosted onJanuary 29, 2013bysqlandplsqlIn Oracle there are many ways to delete duplicate records. Note that below example are described to just explain the different possibilities.Consider the EMP table with below rowscreate table emp(EMPNNO integer,EMPNAME varchar2(20),SALARY number);10 Bill 200011 Bill 200012 Mark 300012 Mark 300012 Mark 300013 Tom 400014 Tom 500015 Susan 50001. Using rowidSQL > delete from empwhere rowid not in(select max(rowid) from emp group by empno);This technique can be applied to almost scenarios. Group by operation should be on the columns which identify the duplicates.2. Using self-joinSQL >delete from emp e1where rowid not in(select max(rowid) from emp e2where e1.empno = e2.empno );3. Using row_number()SQL >delete from emp where rowid in(select rid from(select rowid rid,row_number() over(partition by empno order by empno) rnfrom emp)where rn > 1);This is another efficient way to delete duplicates4. Using dense_rank()SQL >delete from emp where rowid in(select rid from(select rowid rid,dense_rank() over(partition by empno order by rowid) rnfrom emp)where rn > 1);Here you can use both rank() and dens_rank() since both will give unique records when order by rowid.5. Using group byConsider the EMP table with below rows10 Bill 200011 Bill 200012 Mark 300013 Mark 3000SQL >delete from emp where(empno,empname,salary) in(select max(empno),empname,salary from empgroup by empname,salary);This technique is only applicable in few scenarios.Always take extra caution while deleting records.1. First identify the duplicates using select.2. Double verify those are actual duplicates or not3. Take backup ifnecessary4. Apply commit only if you are sure.