Ray Zhang
Ray Zhang

Reputation: 1561

Postgresql: Which is faster: query with OR clause, or two separate queries?

Between these two queries, which one is faster for the database to execute?

select a, b, c from t where x = y or x = z;

vs.

select a, b, c from t where x = y;
select a, b, c from t where x = z;

Either one is fine for my application because the results will be put into a map that will automatically remove duplicates. So then I wonder if there is a technical reason one is more preferable than the other.

Upvotes: 0

Views: 527

Answers (2)

ehrktia
ehrktia

Reputation: 180

As you are selecting same cols from one single table with Two different conditions you can try union operator

Select a,b,c from tab1 where d=cond1 union select a,b,c from tab1 where d=cond2

Upvotes: 1

Gordon Linoff
Gordon Linoff

Reputation: 1270993

They should be pretty much the same if you have an index on x and y and z are constants.

If y and z are columns, then indexes will not help. If no indexes can be used, then the version with or should be about twice as fast, because it scans the table only once rather than twice.

Upvotes: 2

Related Questions