Skip to content
Advertisement

SQL – Returning all rows that are not ‘vice versa’ of one another

I’ve got a situation as follows (note this setup has been created as a minimal reproducible example). I have a table of houses, created like this:

I have a large table called house_listings, like this:

So, let’s say I run the following query:

and I get the following output:

and then I run the following query:

select * from house_listings where house_two = '12345' and I get the following result:

Notice how the first row of this result corresponds to the first row of the other result in a sort of vice-versa way (i.e. in this case house_one and house_two are flipped).

However, what I’m interested in here is the second row of this result. Where house_one is 7777 and house_two and 12345.

I’d like to somehow run a query that will essentially return all rows like the second. So, given a specific house id, like 12345, it would only return (in this example):

I have been experimenting with self joins here, as I think this might be the best way to go, but something joining where house_one = house_two isn’t quite what I want, and I’m not sure how to best approach this issue.

Would appreciate any help here!

Advertisement

Answer

You can use not exists:

This returns all such singletons. You can, of course, add a where clause to the outer query to limit to a particular value of house_one.

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement