Ask Your Question
1

How can I determine in Postgres if a value in one row appears as a value in another row, but in two distinct columns?

asked 2022-02-07 11:00:00 +0000

scrum gravatar image

edit retag flag offensive close merge delete

1 Answer

Sort by ยป oldest newest most voted
1

answered 2021-05-06 23:00:00 +0000

djk gravatar image

You can use a self-join to check if a value in one row appears as a value in another row but in two distinct columns. Here's an example query that demonstrates this:

SELECT t1.column1, t1.column2, t2.column1, t2.column2
FROM mytable t1
INNER JOIN mytable t2 ON t1.column1 = t2.column2 AND t1.column2 = t2.column1
WHERE t1.id <> t2.id;

In this query, we join the table mytable with itself using an inner join. We match rows where t1.column1 equals t2.column2 and t1.column2 equals t2.column1. We also add a condition to exclude rows where t1.id equals t2.id, which prevents matches between the same row.

The result of this query will show you all pairs of rows where the values in two different columns are swapped. For example:

column1 | column2 | column1 | column2
--------+---------+---------+---------
   1    |    2    |    2    |    1
   3    |    6    |    6    |    3

This indicates that the values (1,2) and (2,1) appear in two different rows, as do the values (3,6) and (6,3).

edit flag offensive delete link more

Your Answer

Please start posting anonymously - your entry will be published after you log in or create a new account. This space is reserved only for answers. If you would like to engage in a discussion, please instead post a comment under the question or an answer that you would like to discuss

Add Answer


Question Tools

Stats

Asked: 2022-02-07 11:00:00 +0000

Seen: 9 times

Last updated: May 06 '21