title: A function calculating average age in years in SQL [postgresql]
body: <p>I am trying to create a plpgsql function that calculates the average age (in years) of some persons with ids (integers) stored in another table.</p>
  
  <p>The code is:</p>
  
  <pre><code>begin
  
  DROP TABLE  if EXISTS dates;
  DROP TABLE  if EXISTS tmp;
  DROP TABLE  if EXISTS ages;
  CREATE TABLE ages (age integer);
  
  --(...) In these lines, I create and fill the table tmp. I did not include this code
  --since it's not very much related to my problem. Nevertheless, this table has only
  --one integer column
  
  CREATE TABLE dates AS (SELECT "dateofbirth" from person where "idPerson" in (select "bookedforpersonID" from personsofthistype));
  
  UPDATE  ages  SET (age) = ((SELECT extract (year from age(dateofbirth)) from dates));
  
  return (select avg(age) from age);
  
  end;
  </code></pre>
  
  <p>Of course, <code>dateofbirth</code> is of type <code>date</code>. My problem is that the table ages that is created does not contain anything and thus I cannot return the correct result (the average age of its column). The function's return type is <code>integer</code> (and "Returns set" is not selected in pgadmin).</p>
  
  <p>I am using PostgreSQL 9.3.4, pgAdmin III version 1.18.1.</p>
  
  <p>Thank you.</p>