Skip to content
Advertisement

Order SQL results where each record referencing another record on the same table comes after the referenced record

I have the following data:

Where parent_id is a reference to the SAME table.

I need to sort these columns so that each record is after its parent (not necessarily immediately after).

So I would expect this result:

I’m guessing there is no clean efficient way to do this without any significant schema changes, but in case anybody can think of a method I’m asking this here.

One possible method would be to do multiple queries where each time the parent_id must be in one of the previous queries results. But this wouldn’t be very efficient.

Advertisement

Answer

You will need to recurse to accomplish this:

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