Skip to content
Advertisement

Recursive query in Oracle until a parent in the hierarchy meets a condition?

I have a table like the following:

And I’d like to be able to fetch each ID with its corresponding VALUE_ID. I want to do it in such a way that if a row has a VALUE_ID as NULL, it “inherits” the VALUE_ID of the first parent above it in the hierarchy, that has a VALUE_ID as NOT NULL. So that would be the query result:

Could such a thing be accomplished with only one recursive or hierarchical query? Or be accomplished in general without a procedure, perhaps? With CTE, or CONNECT BY clause?

Advertisement

Answer

You can use a recursive CTE for this:

Here is a db<>fiddle.

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