I am retrieving data and inserting it into another file. But the inserted data is not ordered. Following is the example of what I am trying to achieve.
let $n := <N>
<n>Lemon</n>
<n>Chickoo</n>
<n>Banana</n>
<n>Orange</n>
<n>Pineapple</n>
<n>Apple</n>
<n>Lemon</n>
<n>Chickoo</n>
<n>Banana</n>
</N>
for $x in distinct-values($n/n)
order by $x
return
insert node <n>{$x}</n> into doc('fruits')/fruit
The output of the fruits is as follows –
<fruit>
<n>Lemon</n>
<n>Chickoo</n>
<n>Banana</n>
<n>Orange</n>
<n>Pineapple</n>
<n>Apple</n>
</fruit>
Its not ordered, though mentioned while retrieving… !!!
This is a bug in how BaseX evaluates the
order byFLWOR clause, which is now documented on the GitHub bug tracker. Thereturnclause 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:
Another (probably more elegant) solution is to use
insert nodes, which only has to be evaluated once: