Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Deleting duplicates on combination of two columns in oracle

I have a table for example :
Port Table

S No A Port B port
1 80 100
2 90 110
3 100 80
4 94 106

I want to delete record no. 3 as it is having same combination as record no. 1 how to do this in oracle ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use a single MERGE statement and the ROW_NUMBER analytic function combined with GREATEST and LEAST to find and delete the duplicates:

MERGE INTO table_name dst
USING (
  SELECT ROWID rid,
         ROW_NUMBER() OVER (
           PARTITION BY LEAST(A_Port, B_Port), GREATEST(A_Port, B_Port)
           ORDER BY S_no
         ) AS rn
  FROM   table_name
) src
ON (dst.ROWID = src.rid AND src.rn > 1)
WHEN MATCHED THEN
  UPDATE SET A_port = NULL
  DELETE WHERE 1 = 1;

Which, for your sample data:

CREATE TABLE table_name (S_No, A_Port, B_port) AS
SELECT 1,  80, 100 FROM DUAL UNION ALL
SELECT 2,  90, 110 FROM DUAL UNION ALL
SELECT 3, 100,  80 FROM DUAL UNION ALL
SELECT 4,  94, 106 FROM DUAL;

Will delete the 3rd row.

db<>fiddle here

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading