title: PostgreSQL: Structure of query does not match function result type using polymorphic type "anyelement"
body: <p>Problem: Getting error while returning the selected rows from table using polymorphic type "anyelement".  </p>
  
  <p>Error: structure of query does not match function result type.  </p>
  
  <p>---Table   </p>
  
  <pre><code>CREATE TABLE tes1
  (
      rollno integer,
      fname text,
      lname text,
      age integer,
      branch text,
      phno integer,
      email text,
      address text,
      city text,
      state text,
      country text
  )
  </code></pre>
  
  <p>---Function     </p>
  
  <pre><code>create or replace function fun_test(column_name varchar,relation_name anyelement)
  returns setof anyelement as
  $body$
  declare
          str varchar;
          grouping varchar;
          additional_column varchar;
          select_query varchar;
  begin
         if column_name='fname' then
                 str:=quote_ident(column_name);
                 additional_column:=' max("address") as addr, max("city") as cty, max("state") as st, max("country") as cntry';
             grouping:='"rollno"'||','||quote_ident(column_name);
     else
             str:=quote_ident(column_name);
             additional_column:=' max("address") as addr, max("city") as cty, max("state") as st, max("country") as cntry';
             grouping:='"rollno"'||','||quote_ident(column_name);
     end if;
  
     select_query:= 'select rollno,'||str||','||additional_column||' from '||pg_typeof(relation_name)||
     ' group by '|| grouping;
  
     raise info '%',select_query;
  
     return query execute select_query;
  end;
  $body$
  language plpgsql;
  </code></pre>
  
  <p>---Calling function  </p>
  
  <pre><code> select * from fun_test('fname',NULL::test)
  </code></pre>