title: XQuery to fetch and insert same time
body: <p>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. </p>
  
  <pre><code>let $n := &lt;N&gt;
  &lt;n&gt;Lemon&lt;/n&gt;
  &lt;n&gt;Chickoo&lt;/n&gt;
  &lt;n&gt;Banana&lt;/n&gt;
  &lt;n&gt;Orange&lt;/n&gt;
  &lt;n&gt;Pineapple&lt;/n&gt;
  &lt;n&gt;Apple&lt;/n&gt;
  &lt;n&gt;Lemon&lt;/n&gt;
  &lt;n&gt;Chickoo&lt;/n&gt;
  &lt;n&gt;Banana&lt;/n&gt;
  &lt;/N&gt;
  
  for $x in distinct-values($n/n)
  order by $x 
  return 
      insert node  &lt;n&gt;{$x}&lt;/n&gt; into doc('fruits')/fruit
  </code></pre>
  
  <p>The output of the <code>fruits</code> is as follows - </p>
  
  <pre><code>    &lt;fruit&gt;
              &lt;n&gt;Lemon&lt;/n&gt;
              &lt;n&gt;Chickoo&lt;/n&gt;
              &lt;n&gt;Banana&lt;/n&gt;
              &lt;n&gt;Orange&lt;/n&gt;
              &lt;n&gt;Pineapple&lt;/n&gt;
              &lt;n&gt;Apple&lt;/n&gt;
      &lt;/fruit&gt;
  </code></pre>
  
  <p>Its not ordered, though mentioned while retrieving... !!!</p>