Skip to content
Advertisement

Postgres – How to achieve UNION behaviour with UNION ALL?

I have a table with parent and child ids.

Each parent can have multiple children and each child can have multiple children again.

The data looks like this.

I’d like to find all children. I can use a recursive cte with a UNION ALL.

This gives me the result I’d like to achieve.

However I’d like to include the depth / level and also the path for each node. I can do this using a different recursive cte.

That gives me this data.

My problem is that I have a lot of duplicate data. I’d like to get the same result as the UNION query but with the level and the path.

I tried something like

or

but the first does not change anything and the second returns an error.

Any ideas? Thank you very much!

Advertisement

Answer

Your problem is inappropriate table data. Your table contains the information that 8 is a direct child to 7 twice for instance. I suggest you remove the duplicate data and implement a unique constraint on the pairs.

If you cannot do so for some reason, make the rows distinct in your query:

Demo: https://dbfiddle.uk/?rdbms=postgres_13&fiddle=acb1d7a1a1d26c3fd9caf0e7dedc12b2

(You may also make the columns not nullable. The entries 9|null add no information. If the table were lacking these entries, 9 would still be without a child.)

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