Search code examples
sqloracle-databasehierarchical-data

How do I write this PL/SQL query?


I have a table with 2 columns: Person (1), his/her friends (2).

I need a query to select all of Tom's friends, friends of his friends, friends of their friend and so on... Maybe some SQL or PL/SQL can do this?

For example for Tom this query should return: Sara, Anna, Alex, Lisa.

Person His/Her friends
Tom Sara
Tom Anna
Anna Tom
Anna Alex
Alex Anna
Alex Lisa

Solution

  • You can use a hierarchical query to continue from a friend to a friend or a friend and so on:

    SELECT     DISTINCT friend_name
    FROM       friends
    WHERE      friend_name != 'Tom'
    START WITH name = 'Tom'
    CONNECT BY NOCYCLE PRIOR friend_name = name
    

    EDIT:
    To address the question in the comment about the nocycle option: Without any restriction, a hierarchical query could in theory recurse forever. E.g., with this data, Tome has a friend called Anna. Anna, in turn, has a friend called Tom, and without any restriction, the query could go on indefinitely between these two friends, which will cause it to fail with an "ORA-01436: CONNECT BY loop in user data" error. The NOCYCLE option prevents this repetition and allows the query to complete without "going back" to values it's already visited.