How do you find or delete duplicate rows in a table?


The following SELECT statement will find and display all duplicate rows in a table, except the row with the maximum ROWID. The example uses the dept table:

 

SELECT * FROM dept a

WHERE ROWID <> (SELECT MAX(ROWID)

FROM dept b

WHERE a.deptno = b.deptno

AND a.dname = b.dname — Make sure all columns are compared

AND a.loc = b.loc);

 

The following statement will delete all duplicate rows in a table, except the row with the maximum ROWID:

 

DELETE FROM dept a

WHERE ROWID <> (SELECT MAX(ROWID)

FROM dept b

WHERE a.deptno = b.deptno

AND a.dname = b.dname — Make sure all columns are compared

AND a.loc = b.loc);

 

Alternatively:

 

DELETE FROM dept a

WHERE 1 < (SELECT COUNT(deptno)

FROM dept b

WHERE a.deptno = b.deptno

AND a.dname = b.dname — Make sure all columns are compared

AND a.loc = b.loc);

 

EXPLANATION

===========

Using the pseudocolumn ROWID is the fastest way to access a row. ROWID represents a unique storage identification number for a single row in a table (Note: Two rows on different tables but stored in the same cluster may have the same rowid value).

Advertisements

3 thoughts on “How do you find or delete duplicate rows in a table?

Want to give some comment to author ( Shivmohan Purohit )

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s