1

If I a table:

  X1     X2 
  1       2 
  2       1
  3       2 

I want to remove the duplicated pairs regardless of whether they are in X1 or X2 and to return either

  X1     X2 
  1       2 
  3       2 

or

  X1     X2 
  2       1
  3       2 

Is there a way to do this?

1
  • 2
    Why you have added mysql, sql, oracle, I think your problem is related to a single tag? Commented Aug 23, 2017 at 12:48

3 Answers 3

1

If you have other columns and the pairs only appear once (in either direction):

select t.*
from t
where t.x1 <= t.x2
union all
select t.*
from t
where t.x1 > t.x2 and
      not exists (select 1 from t t2 where t2.x1 = t.x2 and t2.x2 = t.x1);
Sign up to request clarification or add additional context in comments.

Comments

0

Although not part of the SQL standard (which is what the sql tag refers to), most DBMS support the greatest() and least() functions:

select distinct least(x1, x2) as x1, greatest(x1,x2) as x2
from the_table;

3 Comments

Which version of sql server could support greatest() and least() Functions
@Srini131 I think SQL Server is one of the few DBMS to not support that
@ a_horse_with_no_name i tried in sql server i got error,thank you for reply
0

Always select the smallest value first. Do UNION to remove duplicates.

select x, y from table where x <= y
union
select y, x from table where x > y

Comments

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.