0

I have a table named Project in which a parent-child relationship is stored. An entry in the parentprojectid column implies that the respective project instance is a child. The columns of the table are as follows:

projectid, parentprojectid

When I run a SELECT query on this table, the resulting data should consist of every parent followed by all of its children (and the children of its children, if applicable). How do I achieve this?

Here is an example of what the data looks like:

projectid  parentprojid  
proj1      null  
proj11     proj1  
proj12     proj1  
proj121    proj12  
proj2      null  
proj3      null

1 Answer 1

1

Use recursive common table expression, combine all parents into array and then sort by resulting array:

with recursive cte as (
    select t.projectid, t.parentprojid, array[t.projectid::text] as path
    from Table1 as t
    where t.parentprojid is null
    union all
    select t.projectid, t.parentprojid, c.path || t.projectid::text
    from Table1 as t
        inner join cte as c on c.projectid = t.parentprojid
)
select projectid, parentprojid
from cte
order by path

sql fiddle demo

Sign up to request clarification or add additional context in comments.

5 Comments

@a_horse_with_no_name well as far as I see, projectid is already text (varchar actually)
@a_horse_with_no_name yeah, I've tried to find numeric id for some time before realized that this name is id:)
What is the purpose behind converting the path column to an array, when the query runs fine even without conversion to array?
well you can convert it to string, but you have to carefully choose separator, like c.path || '->' || t.projectid::text. Imagine you have two parents - 'A' and 'AA' and children 'A' -> 'AA1' and 'AA' -> 'A1'. IF you concatenate it to string without separators, you'll receive two of 'AAA1'. Using array helps not to think about what separator you'll use.
Thanks working fine :) Got to learn about the recursive concepts

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.