title: Postgres function much slower when using input variables
body: <p>I have a function in Postgres 8.3.5 that selects data from multiple tables and dumps the result in a  single table:</p>
  
  <pre><code>create or replace function test_function_2(startdate timestamp, enddate timestamp)
  returns void as $$
  begin
       delete from cl_final_report;
  
       INSERT INTO cl_final_report
       SELECT 
           b.batchkey AS batchnumber, 
           pv.productkey, 
           p.name AS productname, 
           avg(r.value) AS avgchemlean, 
           sum(r.auxvalue) AS totalweight, 
           max(o.time) AS timecompleted
       FROM result r
       LEFT JOIN physicalvalue pv ON r.physicalvaluekey = pv.physicalvaluekey
       LEFT JOIN product p ON pv.productkey = p.productkey
       LEFT JOIN object o ON r.objectkey = o.objectkey
       LEFT JOIN batch b ON o.batchkey = b.batchkey
       WHERE pv.name = 'CL'::text AND
           and o.time between startdate and enddate
       GROUP BY b.batchkey, pv.productkey, p.name
  end
  $$ language plpgsql;
  </code></pre>
  
  <p>This function takes 113 seconds to complete using PgAdmin and executing this command:</p>
  
  <pre><code>select test_function_2('05/02/2013', '05/03/2013')
  </code></pre>
  
  <p>However, if I replace the input variables in the function with literals like this:</p>
  
  <pre><code>create or replace function test_function_2(startdate timestamp, enddate timestamp)
  returns void as $$
  begin
       delete from cl_final_report;
  
       INSERT INTO cl_final_report
       SELECT 
           b.batchkey AS batchnumber, 
           pv.productkey, 
           p.name AS productname, 
           avg(r.value) AS avgchemlean, 
           sum(r.auxvalue) AS totalweight, 
           max(o.time) AS timecompleted
       FROM result r
       LEFT JOIN physicalvalue pv ON r.physicalvaluekey = pv.physicalvaluekey
       LEFT JOIN product p ON pv.productkey = p.productkey
       LEFT JOIN object o ON r.objectkey = o.objectkey
       LEFT JOIN batch b ON o.batchkey = b.batchkey
       WHERE pv.name = 'CL'::text AND
           and o.time between '05/02/2013' and '05/03/2013'
       GROUP BY b.batchkey, pv.productkey, p.name
  end
  $$ language plpgsql;
  </code></pre>
  
  <p>The function executes in less than 5 seconds.  </p>
  
  <p>I'm new to Postgres so there's probably something I'm missing, but I can't seem to find an answer anywhere.  </p>