tags:

views:

47

answers:

2

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';  -- additional field not indexed
+3  A: 

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.

dcp
::slaps forehead:: yeah, I forgot about that good ol' explain plan.
j0rd4n
A: 

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.

Tony Andrews
Index can get tossed out depending on the statistics for mytable.fielde column. It is possible with the 5th column in the mix a table scan may be cheaper. For a simpler example is here: http://www.dbazine.com/oracle/or-articles/jlewis12
David Mann
@David: regardless of the statistics for fielde, the second query will return at **most** as many rows as query 1, and both require table access due to the "select *". So I stand by my statement that IF query 1 can benefit from the index THEN so can query 2.
Tony Andrews
There's no reason to downvote this answer. Unless you don't love vim, in which case I guess you must :)
Jeffrey Kemp