AlexO
AlexO

Reputation: 11

Optimize sql query which contains 'or'

Query:

select * from t where (a = '..' or a = '..') and b = '..'

Does this query use index (a,b)?

Upvotes: 0

Views: 52

Answers (1)

Gordon Linoff
Gordon Linoff

Reputation: 1271003

First, I would try rewriting this using in:

select *
from t
where a in ('..', '..') and b = '..';

Second, a better index would be t(b, a). There are no issues with b because it only appears once in the where clause with an =.

Third, if these don't speed the query, then use union all:

select *
from t
where a = '..' and b = '..'
union all
select *
from t
where a = '..' and b = '..';

This will get around the limitations on where clause optimization.

Upvotes: 1

Related Questions