Skip to content
Advertisement

Unique combination of records in a SQL table (Get edges from nodes table)

I came across a use case where I wanted to generate a combination table where the attributes of a record had to be matched with all other records in the table. Something like creating list of edges in a Complete Graph using a nodes table.

enter image description here

To give you an example of the requirement, you can consider the following table (Postgres).

I added some records into the table using the following insert queries

And you’ll get the following table in place

Now I want to create a combination of these names in such a way that the first_name of a row should have all the possible combination available such that (f1, f2) = (f2, f1). To give you some more context the expected output should be as follows.

You can see that the combination of column 1 and column 2 for first_name is unique in the table.

The closest that I was able to reach was to have an inner join using the following query.

But this yields all the records where (f1, f2) != (f2, f1) hence creating redundant records. Is there a way to get unique list of edges from the list of nodes in a Complete Graph using SQL?

Advertisement

Answer

Just use < (or >) instead of <>in the join condition:

Notes:

  • you probably want to alias the column in the resultset to disambiguate the columns coming from both tables

  • no need for a left join – an inner join does what you want

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