OR vs UNION - Mailing list pgsql-sql

From Scott Cain
Subject OR vs UNION
Date
Msg-id 1058465506.3345.15.camel@localhost.localdomain
Whole thread Raw
Responses Re: OR vs UNION  (Josh Berkus <josh@agliodbs.com>)
List pgsql-sql
Hello,

I have a query that uses a series of ORs and I have heard that sometimes
this type of query can be rewritten to use UNION instead and be more
efficient.  Are there any rules of thumb for when this might be the
case?  As an example here is a query of the type I am discussing:
    select distinct f.name,fl.fmin,fl.fmax,fl.strand,f.type_id,f.feature_id    from feature f, featureloc fl    where
  (f.type_id = 219 OR       f.type_id = 368 OR       f.type_id = 514 OR       f.type_id = 475 OR       f.type_id = 426
OR      f.type_id = 456 OR       f.type_id = 461 OR       f.type_id = 553 OR       f.type_id = 89) and
fl.srcfeature_id= 1 and     f.feature_id  = fl.feature_id and     fl.fmin <= 2491413 and fl.fmax >= 2485521
 

which could easily be rewritten as a set of select statements for each
type_id and then union them together.  For this particular query,
explain analyze indicates that this is the more efficient form, but I
could easily see that at other times/for other parameters, a set unioned
together would be better.  Are there any guidelines for this?

Thanks,
Scott

-- 
------------------------------------------------------------------------
Scott Cain, Ph. D.                                         cain@cshl.org
GMOD Coordinator (http://www.gmod.org/)                     216-392-3087
Cold Spring Harbor Laboratory



pgsql-sql by date:

Previous
From: Joe Conway
Date:
Subject: Re: Recursive request ...
Next
From: Richard Huxton
Date:
Subject: Re: Table Partitioning and Rules