开发者

In Oracle, will a compound index still be used if a where clause contains some additional fields?

开发者 https://www.devze.com 2022-12-22 05:17 出处:网络
So let\'s say I have a compound index on a table that indexes 4 fields. create index idx_comp_index on mytable ( fielda, fieldb, fieldc, fieldd );

So let's say I have a compound index on a table that indexes 4 fields.

create index idx_comp_index
on mytable ( fielda, fieldb, fieldc, fieldd );

If I query that table using all four of those fields in my where clause plus an additional field or two, will the index still be used?

select *
from mytable
where fielda = 'i'
  and fieldb = 'love'
  and fieldc = 'vim'
  and fieldd = 'so'
  and fielde = 'much'; 开发者_Go百科 -- additional field not indexed


The answer is, "it depends". The best way to determine such things is to look at the optimizer plan, which will tell you the query plan, along with what indexes are being used.

Check out "explain plan" on google.

Whether or not Oracle will use an index basically comes down to whether the optimizer determines that it's more expensive to use the index than not to use it. In some cases, the optimizer may determine it's faster not to use the index, and most of the time, the optimizer is exactly right.

The other things to take into account are to make sure you have up to date statistics on your tables, since that is what the optimizer uses to determine the query plan.


Certainly, if this uses an index:

select *
from mytable
where fielda = 'i'
  and fieldb = 'love'
  and fieldc = 'vim'
  and fieldd = 'so';

then I see no reason why this would not:

select *
from mytable
where fielda = 'i'
  and fieldb = 'love'
  and fieldc = 'vim'
  and fieldd = 'so'
  and fielde = 'much';  -- additional field not indexed

If instead of "select *" you had "select fielda" then the query without fielde might be answered using only the index, whereas the query with fielde could not.

0

精彩评论

暂无评论...
验证码 换一张
取 消