title: Preserve the order of distinct inside string_agg
body: <p>My SQL function:</p>
  
  <pre><code>with recursive locpais as (
      select l.id, l.nome, l.tipo tid, lp.pai
      from loc l
      left join locpai lp on lp.loc = l.id
      where l.id = 12554
      union
      select l.id, l.nome, l.tipo tid, lp.pai
      from loc l
      left join locpai lp on lp.loc = l.id
      join locpais p on (l.id = p.pai)
  )
  select * from locpais
  </code></pre>
  
  <p>gives me</p>
  
  <pre><code>12554 |     PARNA Pico da Neblina | 9 | 1564
  12554 |     PARNA Pico da Neblina | 9 | 1547
   1547 |  São Gabriel da Cachoeira | 8 | 1400
   1564 | Santa Isabel do Rio Negro | 8 | 1400
   1400 |                 RIO NEGRO | 7 |  908
    908 |          NORTE AMAZONENSE | 6 |  234
    234 |                  Amazonas | 5 |  229
    229 |                     Norte | 4 |   30
     30 |                    Brasil | 3 |
  </code></pre>
  
  <p>which is a hierarchy of places. "PARNA" stands for "National Park", and this one covers two cities: São Gabriel da Cachoeira and Santa Isabel do Rio Negro. Thus it's appearing twice.</p>
  
  <p>If I change the last line for</p>
  
  <pre><code>select string_agg(nome,', ') from locpais
  </code></pre>
  
  <p>I get</p>
  
  <blockquote>
    <p>"PARNA Pico da Neblina, PARNA Pico da Neblina, São Gabriel da
    Cachoeira, Santa Isabel do Rio Negro, RIO NEGRO, NORTE AMAZONENSE,
    Amazonas, Norte, Brasil"</p>
  </blockquote>
  
  <p>Which is almost fine, except for the double "PARNA Pico da Neblina". So I tried:</p>
  
  <pre><code>select string_agg(distinct nome, ', ') from locpais
  </code></pre>
  
  <p>but now I get</p>
  
  <blockquote>
    <p>"Amazonas, Brasil, Norte, NORTE AMAZONENSE, PARNA Pico da Neblina, RIO
    NEGRO, Santa Isabel do Rio Negro, São Gabriel da Cachoeira"</p>
  </blockquote>
  
  <p>Which is out of order. I'm trying to add an <code>order by</code> inside the <code>string_agg</code>, but couldn't make it work yet. The definition of the tables were given <a href="https://stackoverflow.com/q/35702246/1086511">here</a>.</p>