Db2 – Remove all records with duplicates in db2. (Not just the duplicate records)

db2deleteduplication

How can I remove all the records with duplicates in db2. I have looked at various answers but they only remove the duplicates leaving one record from that set in the table. This is what I found already.

DELETE FROM
(SELECT ROWNUMBER() OVER (PARTITION BY ONE, TWO, THREE) AS RN
FROM SESSION.TEST) AS A
WHERE RN > 1;

But, I need a query that will remove all the records that contain duplicates not leaving behind one of them in the table.

A A 1 <– delete this
A A 2 <– delete this too
B B 3
C C 4

P.S: Using RN >= 1 does not work as it will make the table empty by deleting all records.

Best Answer

Assuming your desired uniqueness constraint is (one,two), here is one way to do it:

DELETE FROM session.test WHERE (one, two) IN ( SELECT one, two FROM session.test GROUP BY one, two HAVING COUNT(*) > 1 )