Skip to content
Advertisement

Postgres recursive query – get path to root given a leaf node

I have a leaf node in a tree structure and I need a Postgres query to recursively traverse the parent nodes to get me the full path to my leaf node.

My table looks like this – the problem being there is no specific root node (i.e the top-most managers end up reporting to each other)

Given a user such as Bill (id=5) I’m after their reporting line:

Matt > Simon > Bob > Bill (ideally it just stops at Matt when it tries to go to a node already traversed)

Advertisement

Answer

A recursive CTE is what you’re looking for.

Data sample

Query

Demo: db<>fiddle

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