Received: from maia.hub.org (maia-3.hub.org [200.46.204.243]) by mail.postgresql.org (Postfix) with ESMTP id 2A5F3B5DBF0 for ; Fri, 28 Oct 2011 02:10:16 -0300 (ADT) Received: from mail.postgresql.org ([200.46.204.86]) by maia.hub.org (mx1.hub.org [200.46.204.243]) (amavisd-maia, port 10024) with ESMTP id 80437-03 for ; Fri, 28 Oct 2011 05:10:09 +0000 (UTC) X-Greylist: from auto-whitelisted by SQLgrey-1.8.0-rc2 Received: from sss.pgh.pa.us (sss.pgh.pa.us [66.207.139.130]) by mail.postgresql.org (Postfix) with ESMTP id AE185B5D91F for ; Fri, 28 Oct 2011 02:10:09 -0300 (ADT) Received: from sss2.sss.pgh.pa.us (tgl@localhost [127.0.0.1]) by sss.pgh.pa.us (8.14.2/8.14.2) with ESMTP id p9S5A8jl014400; Fri, 28 Oct 2011 01:10:08 -0400 (EDT) To: CS DBA cc: pgsql-performance@postgresql.org Subject: Re: function slower than the same code in an sql file In-reply-to: <4EAA3597.3020202@consistentstate.com> References: <4EAA3597.3020202@consistentstate.com> Comments: In-reply-to CS DBA message dated "Thu, 27 Oct 2011 22:54:47 -0600" Date: Fri, 28 Oct 2011 01:10:08 -0400 Message-ID: <14399.1319778608@sss.pgh.pa.us> From: Tom Lane X-Virus-Scanned: Maia Mailguard 1.0.1 X-Spam-Status: No, hits=-2.404 tagged_above=-10 required=5 tests=BAYES_00=-1.9, RP_MATCHES_RCVD=-0.504 X-Spam-Level: X-Archive-Number: 201110/242 X-Sequence-Number: 45464 CS DBA writes: > I have code that drops a table, re-create's it (based on a long set of > joins) and then re-creates the indexes. > It runs via psql in about 10 seconds. I took the code and simply > wrapped it into a plpgsql function and the function version takes almost > 60 seconds to run. > I always thought that functions should run faster than psql... am I wrong? Did you really just put the identical queries into a function, or did you parameterize them with values passed to the function? Parameterized queries are often slower due to the planner not knowing the specific constant values that are used in the actual calls. There's some work done for 9.2 to improve that, but in existing releases you typically have to construct dynamic queries and EXECUTE them if you run into this problem. regards, tom lane