Re: Short circuit evaluation of expressions in query

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: "Jimmy Choi" <JCHOI(at)altera(dot)com>
Cc: pgsql-general(at)postgresql(dot)org
Subject: Re: Short circuit evaluation of expressions in query
Date: 2006-06-14 04:08:31
Message-ID: 19747.1150258111@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

"Jimmy Choi" <JCHOI(at)altera(dot)com> writes:
> Say I have the following parameterized query in a function:
> select * from foo where ($1 = -1 or foo.status = $1) and (...)

> Suppose that at runtime, $1 is supplied a value of -1, does the
> foo.status = $1 condition still have to be evaluated?

The PG manual points out that left-to-right short circuit is NOT part of
the language specification:
http://www.postgresql.org/docs/8.1/static/sql-expressions.html#SYNTAX-EXPRESS-EVAL

However, the real problem with thinking as you do above is that it's
micro-optimization on the wrong level. Usually the sort of optimization
you need to think about in SQL is whether the query allows an index to
be used to fetch the relevant rows. In the above, even if you have an
index on foo.status, it won't be used because the OR means that
potentially *every* row of foo matches the OR condition.

If you really have a need to sometimes fetch all the rows and sometimes
fetch only the ones with status = X, I'd suggest generating different
queries in those two cases.

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Casey, J Bart 2006-06-14 05:08:18 Problem Connecting to 5432
Previous Message jdwatson1@gmail.com 2006-06-14 03:31:02 Re: Searching BLOB - Lucene setup & problem