 <p>This is because you're using a <code>DISTINCT</code> in your <code>SELECT</code> query. If you look at the execution plan, you can see <code>DISTINCT SORT</code> operation. This sorts your result based on the <code>DISTINCT</code> columns you specify, in this case it's <code>Name</code>:</p> <p><img src="https://i.stack.imgur.com/0zHNV.png" alt="enter image description here"></p> <p>To retain the order, you can try this:</p> <pre><code>set @var = stuff(( select ',' + name from( select name, drn, rn = row_number() over(partition by name order by drn) from temp )t where rn = 1 order by drn for xml path('')), 1,1,'') </code></pre>