Skip to content
Advertisement

Overwriting nulls with parent data in a hierarchical query

I have a table with the following format:

pk is the primary key for each row, fk is a foreign key to another table I’ll need to join later, and parent is the record’s hierarchical parent. I can create a hierarchical query on this data with

My question is how do I overwrite a row’s null foreign key with that of the lowest ancestor without a null? My intended output in this scenario is

(primary keys padded to show hierarchical structure.)

Advertisement

Answer

You could express this with a standard recursive common table expression:

Demo on DB Fiddlde:

PK    | FK | PARENT
:---- | -: | -----:
1     | 23 |      0
  2   | 23 |      1
  3   | 46 |      1
4     | 12 |      0
  5   | 12 |      4
    6 | 12 |      5
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement