I'm trying to figure out how to use a recursive query with a hierarchical table. I need to get the ancestors of a given record, and the records should be sorted in order of their level in the hierarchy. That is, the first record should be the top node, the next should be a child, then its child, down to the record being queried.
Consider a table called "food" with the following data. It's a simple hierarchy, with every record except the top record having a parent record.
id | parent
-----------+---------
top |
fruit | top
red | fruit
cherry | red
apple | red
orange | fruit
clementine | orange
mandarin | orange
Trying to understand the various web pages on the topic, I cobbled together the following query which gives all the ancestors for the "mandarin" record, including the mandarin record itself.
with recursive
child_record(id) as (
values('mandarin')
union
select parent
from food, child_record
where food.id = child_record.id
)
select id from food
where food.id in child_record;
However, that query returns the record in what appears to me to be an arbitrary order:
fruit
mandarin
orange
top
I'd like the records to be sorted with the top record first, down the levels to the mandarin record.
top
fruit
orange
mandarin
How do I structure that query to give the records in the order I want?