Re: left join with OR optimization

From: Tom Lane <tgl(at)sss(dot)pgh(dot)pa(dot)us>
To: Sim Zacks <sim(at)compulab(dot)co(dot)il>
Cc: PostgreSQL general <pgsql-general(at)postgresql(dot)org>
Subject: Re: left join with OR optimization
Date: 2012-01-24 15:27:41
Message-ID: 5452.1327418861@sss.pgh.pa.us
Views: Raw Message | Whole Thread | Download mbox | Resend email
Thread:
Lists: pgsql-general

Sim Zacks <sim(at)compulab(dot)co(dot)il> writes:
> I've seen written that a b-tree index can't be used on a join with an
> OR.

That's not the case ...

> Is there a way to optimize a join so that it can use an index for a
> query such as:

> select
> a.partid,a.duedate,coalesce(a.quantity,0)+sum(coalesce(b.quantity,0))
> from stat_allocated_components a
> left join stat_allocated_components b on a.partid=b.partid and
> b.quantity>0 and
> (a.duedate>b.duedate or (a.duedate=b.duedate and a.popartid>b.popartid))
> where a.quantity>0
> group by a.partid,a.duedate,a.quantity

... but in this example, it would be both more readable and more easily
optimizable if you expressed the duedate/popartid requirement as a row
comparison:

row(a.duedate, a.popartid) > row(b.duedate, b.popartid)

regards, tom lane

In response to

Browse pgsql-general by date

  From Date Subject
Next Message Chris Angelico 2012-01-24 16:50:25 Re: Best way to create unique primary keys across schemas?
Previous Message David Johnston 2012-01-24 15:27:25 Re: left join with OR optimization