X-Original-To: pgsql-admin@postgresql.org Received: from megazone.bigpanda.com (megazone.bigpanda.com [63.150.15.178]) by postgresql.org (Postfix) with ESMTP id 6BF60476657 for ; Wed, 12 Mar 2003 17:10:39 -0500 (EST) Received: by megazone.bigpanda.com (Postfix, from userid 1001) id 15EECD60A; Wed, 12 Mar 2003 14:10:41 -0800 (PST) Received: from localhost (localhost [127.0.0.1]) by megazone.bigpanda.com (Postfix) with ESMTP id 0BBCE5C04; Wed, 12 Mar 2003 14:10:41 -0800 (PST) Date: Wed, 12 Mar 2003 14:10:41 -0800 (PST) From: Stephan Szabo To: Chris Mungall Cc: Subject: Re: Using functions as filters in queries In-Reply-To: <20030312135522.G56401-100000@megazone23.bigpanda.com> Message-ID: <20030312140421.O56401-100000@megazone23.bigpanda.com> MIME-Version: 1.0 Content-Type: TEXT/PLAIN; charset=US-ASCII X-Archive-Number: 200303/159 X-Sequence-Number: 7799 On Wed, 12 Mar 2003, Stephan Szabo wrote: > > On Mon, 10 Mar 2003, Chris Mungall wrote: > > > I have a problem that can be reduced to this equivalent but simpler > > problem: > > > EXPLAIN ANALYZE select * from t where n=5 AND x like 'a%'; > > 5 is a constant. > > > Case 2: > > > > Now I want to replace the "n=5" clause with a function: > > > > CREATE FUNCTION f(t, int) RETURNS bool AS > > 'SELECT $1.n = $2' > > LANGUAGE 'sql'; > > > > EXPLAIN ANALYZE select * from t where f(t, 5) AND x like 'a%'; > > > > Now looking at the two cases (without and with function) I can see that > > they are equivalent, but Pg treats them differently. I guess it is failing > > to distiguish between two cases - if the function has no FROM clause, then > > it is a simple case of variable substitution into the original WHERE > > clause. If it does include a FROM clause, it's not so simple and > > optimisation is hard, so the function becomes the filter. > > It doesn't look at the contents of the function. It looks at whether the > function is defined IMMUTABLE, STABLE or VOLATILE. With a VOLATILE > function (the default), the system is not guaranteed that given the > same arguments that the result is the same. You might want to read > the description in the manpage for CREATE FUNCTION. Of course, I misread what explain did (without trying the enable_seqscan=off case) and this is still not indexable because even after that, you'll not get a clause on the outside that it considers indexable. It is smart enough (7.4 anyway) to make the filter ((t.*).n)=5 which I thought it'd index, but doesn't. :(