This is an exemple of your table. SELECT * FROM (VALUES (1, 2), (2, 1), (3, 4), (4, 1)) t (id1, id2) id1 |id2 | ------+------+ 1| 2| 2| 1| 3| 4| 4| 1| I think that is what you need SELECTDISTINCTLEAST(id1, id2) ASid1, GREATEST(id1, id2) ASid2 FROM (VALUES (1, 2), (2, 1), (3, 4), (4, 3)) t (id1, id2) id1 |id2 | ------+------+ 1| 2| 3| 4|
I'll let OP clarify, but in your dataset example (not the same as original), shouldn't "4, 1" be found also. It's a unique pair (whereas "1,2" and "2,1" are repeating when sorted low/high). Which makes me think that merging the two columns into an array, sorting the array, and then squasing duplicates would do the job? Maybe there's an easier way, but from what I can see of the original requirements, your dataset should return the following?