title: SQL - call aggregate function in sort order
body: <p>I have a custom aggregate function that concatenates items with a delimiter.
  How can I call this function to ensure that the result is a sorted list.</p>
  
  <p>Aggregate functions like sum() will have the same result no matter which order the rows are fed to it. </p>
  
  <p>I can't easily sort the items in the aggregate function itself because the sort order depends on a different field. </p>
  
  <p>For example:</p>
  
  <pre><code>product|size_id   | size_string
  --------------------------------
  prod1  |10        | x-small
  prod1  |20        | small
  prod1  |30        | medium
  prod1  |40        | large
  prod1  |50        | x-large
  </code></pre>
  
  <p>I would like a query to return:</p>
  
  <blockquote>
    <p>prod1, available in:
    x-small,small,medium,large,x-large</p>
  </blockquote>
  
  <p>I.e. in the sizes concatenated in the order of (size_id)</p>
  
  <pre><code>SELECT product,concat_agg(size_string) GROUP BY product;
  </code></pre>
  
  <p>will return the required data, but not in sorted order.</p>
  
  <p>At the moment I'm using a function to cycle through the sizes in the correct order and adding them to the result. I suspect there might be an SQL way to have a subquery produce the desired result. There must be other aggregate functions that are not commutative.</p>