Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter SQL query by a unique set of column values, regardless of their order

Tags:

sql

oracle

I have a table in Oracle containing two columns that I'd like to query for records containing a unique combination of values, regardless of the order of those values. For example, if I have the following table:

create table RELATIONSHIPS (
    PERSON_1 number not null,
    PERSON_2 number not null,
    RELATIONSHIP  number not null,
    constraint PK_RELATIONSHIPS
        primary key (PERSON_1, PERSON_2)
);

I'd like to query for all unique relationships. So if I have a record PERSON_1 = John and PERSON_2 = Jill, I don't want to see another record where PERSON_1 = Jill and PERSON_2 = John.

Is there an easy way to do this?

like image 647
Kevin Babcock Avatar asked Dec 13 '22 04:12

Kevin Babcock


1 Answers

Is the relationship always there in both directions? i.e. if John and Jill are related, then is there always a {John,Jill} and {Jill,John} ? If so, just limit to those where Person_1 < Person_2 and take the distinct set.

like image 66
Marc Gravell Avatar answered Jan 04 '23 23:01

Marc Gravell