Re: Does psql evaluate OR conditions in order?

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: HideMe <r36(at)tara-lu(dot)com>
Cc: pgsql-novice(at)postgresql(dot)org
Subject: Re: Does psql evaluate OR conditions in order?
Date: 2013-01-16 21:40:10
Message-ID: 3039.1358372410@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-novice

HideMe <r36(at)tara-lu(dot)com> writes:
> Postgres 9.1
> Ubuntu something.

> We have a stored procedure that performs the following evaluations:

> IF ST_Intersects(line1, line2) OR ST_Intersects(line3, line4) THEN
> do stuff
> ELSIF ST_Intersects(line5, line6) OR ST_Intersects(line7, line8) THEN
> do stuffB
> END IF;

> 98% of the time the 2nd half of these IF statements will never be true.
> ST_Intersects is an expensive operations to perform.

> Given we're executing this across a lot of data... avoiding expensive
> calls is a good idea.
> So, can we count on the evaluation of the 1st half of the IF's being
> done first before trying the 2nd half,

In principle the order of ORs is not guaranteed, but that mainly has to
do with execution of query WHERE clauses, wherein the optimizer will
feel free to move sub-clauses to different relations, join levels, etc.
I think you're reasonably safe to assume that OR is left-to-right in
this simple context.

> or should we re-write the IF/ELSE to

> IF ST_Intersects(line1, line2) THEN
> do stuff
> ELSIF ST_Intersects(line5, line6) THEN
> do stuffB
> ELSIF ST_Intersects(line3, line4) THEN
> do stuff
> ELSIF ST_Intersects(line7, line8) THEN
> do stuffB
> END IF;

That doesn't look like it produces quite the same results ...

regards, tom lane

In response to

Responses

Browse pgsql-novice by date

  From Date Subject
Next Message Roxanne Reid-Bennett 2013-01-16 23:41:17 Re: Does psql evaluate OR conditions in order?
Previous Message HideMe 2013-01-16 21:04:59 Does psql evaluate OR conditions in order?