0

I have following table. I want to delete duplicate rows and keep the one that has Name1 = Name2. So, in the example below row 2 and 4 should be removed.

ID | Name1 | Name2
 1 | n1    |  n1
 1 | n1    |  n2
 2 | n1    |  n1
 2 | n1    |  n2

How can I do this with SQL query ?

1 Answer 1

1

I think this does what you want:

delete from t
    where t.name1 <> t.name2 and
          exists (select 1
                  from t t2 
                  where t2.id = t.id and
                        t2.name1 = t2.name2
                 );

If you just want a select, that can be done similarly:

    select t.*
    from t
    where t.name1 = t.name2 or
          not exists (select 1
                      from t t2 
                      where t2.id = t.id and
                            t2.name1 = t2.name2
                     );
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks ! This works but can I ask you a related question here?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.