The following sql snippets try to demonstrate how SQLite allows to hierarchically select a result set where siblings (records with the same parent record) are ordered by a specific criteria.
This is the table that we're going to select from.
pos is the ordering of records with the same parent.
Since we want the ordering of the siblings to be determinated, we place a unique constraint for parent and pos.
drop table if exists item;
create table item (
id integer not null primary key,
parent integer null references item,
txt text not null,
pos integer not null,
unique(parent, pos)
);
The «trick» to achieve the desired ordering of the siblings is to order the level descending and the position ascending:
with recursive items (lvl, id, txt, pos) as (
select
0 as lvl,
id,
txt,
pos as pos
from
item
where
parent is null
union all
select
items.lvl + 1,
item.id,
item.txt,
item.pos
from
items join
item on items.id = item.parent
order by
items.lvl+1 desc,
item.pos
)
select
substr('_________________', 1, lvl*2) || txt
from
items;