Search code examples
sqlsetunordered

How to remove opposite rows from SQL table


I have the following SQL table:

A|B
---
w|x
x|w
y|z
z|y

Can I construct a query which will yield the following result:

A|B
---
w|x
y|z

To summarize, I would like to treat the two columns as an unordered set, such that (a,b) == (b,a).


Solution

  • The "best" code depends on the database, but following is dbms-agnostic:

    SELECT      t.A,
                t.B
    FROM        my_table t
    LEFT JOIN   my_table t2
            ON  t.A = t2.B
            AND t.B = t2.A
            AND t.A < t.B
    WHERE       t2.A IS NULL