This is a bug in how BaseX evaluates the order by
FLWOR clause, which is now documented on the GitHub bug tracker. The return
clause is evaluated before sorting instead of afterwords, thus adding the updates in the wrong order.
A workaround would be to either do the sorting in another FLWOR expression:
for $x in
for $d in distinct-values($n/n)
order by $d
return $d
order by $x
return
insert node <n>{$x}</n> into doc('fruits')/fruit
Another (probably more elegant) solution is to use insert nodes
, which only has to be evaluated once:
insert nodes
for $x in distinct-values($n/n)
order by $x
return <n>{$x}</n>
into doc('fruits')/fruit