title: postgresql order by similarity (trigrams) on 2 fields
body: <p>I used trigrams on 2 fields in my table and want to sort by MAX similarity comparing both fields during the request.(Postgresql 11.x)</p>
  <p>I have difficulties to do this:</p>
  <ul>
  <li>I can't use aliases in order by</li>
  <li>If I replace full code by similarity(...) I have this error:</li>
  </ul>
  <blockquote>
  <p>Query 1 ERROR: ERROR:  for SELECT DISTINCT, ORDER BY expressions must
  appear in select list</p>
  </blockquote>
  <p>My current request with aliases not working in ORDER BY of godd is:</p>
  <pre><code>SELECT DISTINCT
  similarity (msr_references.searchable, 'my simple test') AS similarity,
  similarity (msr_references.simplified_searchable, 'my simple test') AS similarity_simplified,
  msr_references.name, msr_references.searchable, msr_references.simplified_name, msr_references.simplified_searchable
  FROM
      &quot;msr_references&quot;
  WHERE 
      similarity(msr_references.searchable, 'my simple test') &gt;= 0.3
      OR
      similarity(msr_references.simplified_searchable, 'my simple test') &gt;= 0.3
  ORDER BY
      CASE WHEN similarity &gt;= similarity_simplified THEN similarity END DESC,
      CASE WHEN similarity_simplified &gt;= similarity THEN similarity_simplified END DESC
  LIMIT 10;
  </code></pre>
  <p>The goal of the request is to sort by MAX similarity between the 2 fields, but for all records.</p>
  <p>Example of good sorting:</p>
  <pre><code>similarity | similarity_simplified
  0.3          0.55
  0.51         0.2
  0.46         0.31
  0.32         0.43
  0.39         0.36
  </code></pre>
  <p>Is this possible technically ?
  Thanks,</p>