From: Tom Lane <tgl@sss.pgh.pa.us>
To: Brett W. McCoy <bmccoy@chapelperilous.net>
Cc: Bolt Thrower <tyr@teiresias.net>
Cc: pgsql-admin@postgresql.org
Subject: Re: SQL question
Date: Fri, 01 Feb 2002 19:28:02 -0500
Message-ID: <14041.1012609682@sss.pgh.pa.us> (raw)
In-Reply-To: <Pine.LNX.4.43.0202011848350.2469-100000@chapelperilous.net>
References: <Pine.LNX.4.43.0202011848350.2469-100000@chapelperilous.net>
"Brett W. McCoy" <bmccoy@chapelperilous.net> writes:
>> select field, length(field) from table where length(field) < 10;
>>
>> How many times is the length() function called for each row? Once or
>> twice?
> I would expect it to run both times.
More specifically, the one in the select list will be evaluated at
every row where the WHERE clause succeeds. So "twice per row" is
an overstatement, possibly a large overstatement.
Also, although PG is not smart about common subexpressions in the way
that Bolt is evidently hoping, it does know all about Boolean
short-circuiting. If you have something like
select ... from table where foo = 42 and length(bar) < 10
then length(bar) will not get evaluated at rows where foo = 42 fails.
Note: this assumes that the planner does not choose to reorder the
WHERE clauses, which AFAIR it'd only do if it pulls out a WHERE clause
to use with an index. For example, if there's an index on foo,
the clause foo = 42 will probably get pulled out and used for an
indexscan (thus, in effect, "evaluated first") no matter whether you
write it first or second.
An interesting point here is that in the presence of functional indexes,
"avoiding the function evaluation" is not necessarily what you want.
We could imagine having an index on length(bar), in which case
where length(bar) < 10
reduces to a scan over the part of the index that has entries less than
10. I'm not sure this would be a win for length(), but for expensive
functions that have a wider variation in probable values than length()
does, it can be a huge win.
regards, tom lane
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Reply to all the recipients from your mail client; the link fills in
the headers below: reply via email
Some clients, webmail especially, drop In-Reply-To and References from
a link, and the reply then starts a new thread: use the mbox below.
To: pgsql-admin@postgresql.org
Cc: tgl@sss.pgh.pa.us, bmccoy@chapelperilous.net, tyr@teiresias.net
Subject: Re: SQL question
In-Reply-To: <14041.1012609682@sss.pgh.pa.us>
References: <Pine.LNX.4.43.0202011848350.2469-100000@chapelperilous.net> <14041.1012609682@sss.pgh.pa.us>
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox