Skip to content
Advertisement

Iterating multiple times over same table (postgres sql)

i am working with sql from few days as beginner and stuck at a problem!

Problem:

  • Given A table user_email_table which columns are (id, user_id, user_id_email)
  • How to get all user co-related to each and every user extending himself

user_email_table

Desired Output

Please Ignore validate data of email fields This are just for reminding to mention these columns in output-table

What SQL query can result into this table

Advertisement

Answer

You want a “cross join” of the table against itself excluding the self-matching rows. You can do:

EDIT:

As @IMSoP points out the query can also use a common join with a join predicate and can be rephrased as:

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