title: Cast a PostgreSQL column to stored type
body: <p>I am creating a viewer for PostgreSQL. My SQL needs to sort on the type that is normal for that column. Take for example:</p>
  
  <p>Table:</p>
  
  <pre><code>CREATE TABLE contacts (id serial primary key, name varchar)
  </code></pre>
  
  <p>SQL:</p>
  
  <pre><code>SELECT id::text FROM contacts ORDER BY id;
  </code></pre>
  
  <p>Gives:</p>
  
  <pre><code>1
  10
  100
  2
  </code></pre>
  
  <p>Ok, so I change the SQL to:</p>
  
  <pre><code>SELECT id::text FROM contacts ORDER BY id::regtype;
  </code></pre>
  
  <p>Which reults in:</p>
  
  <pre><code>1
  2
  10
  100
  </code></pre>
  
  <p>Nice! But now I try:</p>
  
  <pre><code>SELECT name::text FROM contacts ORDER BY name::regtype;
  </code></pre>
  
  <p>Which results in:</p>
  
  <pre><code>invalid type name "my first string"
  </code></pre>
  
  <p>Google is no help. Any ideas? Thanks</p>
  
  <p><strong>Repeat</strong>: the error is not my problem. My problem is that I need to convert each column to <code>text</code>, but order by the normal type for that column.</p>