Skip to Main Content
  • Questions
  • Does DISTINCT(X) or MAX(X) can use the index?

Breadcrumb

Question and Answer

Tom Kyte

Thanks for the question.

Asked: July 15, 2005 - 10:08 pm UTC

Last updated: July 29, 2005 - 12:31 pm UTC

Version: 8.1.7

Viewed 1000+ times

You Asked

Hi Tom,

Table A :

create table a (a number, b number)

Index :

create index idx_1 on a (a number, b number)
create index idx_2 on a (a number)

Query :

select distinct(b) from a where a = 100

In this case, which index idx_1 or idx_2 should be built? I found that the query can use idx_1 and idx_2 (assume only one index is built on table a). Can Oracle use idx_1 in the where cause and then use idx_1 again in distinct(b) (or similiar max(b))?

Thanks
David

and Tom said...



If the goal were to make the

select distinct(b) from t where a = 100;

as fast as possible and a=100 was "selective" (did not hit too much of the table) then the index in (a,b) would be most effective.

and yes, it could be used for max(b) where a=100 as well.

Rating

  (3 ratings)

Is this answer out of date? If it is, please let us know via a Comment

Comments

How index on column b will be useful when it is not in WHERE?

A reader, July 29, 2005 - 4:03 am UTC

insert into a values(&a,&b);

-- Created both indexes.

select * from a;
A B
---------- ----------
100 1
200 1
300 3
300 5
600 6
100 8

6 rows selected.

interspc@spex.NNVH023A> select distinct(b) from a where a = 100 ;

B
----------
1
8

2 rows selected.

Auto trace result shows..

Execution Plan
----------------------------------------------------------
0 SELECT STATEMENT Optimizer=RULE
1 0 SORT (UNIQUE)
2 1 TABLE ACCESS (BY INDEX ROWID) OF 'A'
3 2 INDEX (RANGE SCAN) OF 'IDX_2' (NON-UNIQUE)


Could you please explan how index on b is useful get to distinct(b)?

Thanks



Tom Kyte
July 29, 2005 - 8:44 am UTC

well, we have to guess since you don't provide the entire example.

idx_2 is on A.

idx_2 is used to find rowids of rows such that a=100

this rowid we find is in turn used to get the row (table access by index rowid)

we get the row which has B on it (and such that a=100, we know that from the index)

and distinct it.

How can we see the use of idx_1 ?

A reader, July 29, 2005 - 9:43 am UTC

I created both the indexes as in the original Question. Sorry for not mentioning that.
ie, create index idx_1 on a (a,b)
and create index idx_2 on a (a)

Will it be possible to see the use of index on column b(Here index idx_1) in getting DISTINCT(b) values ? Just curious to know that.

As always, Thanks.




Tom Kyte
July 29, 2005 - 12:30 pm UTC

yes, use the cbo and you'll be happier.

when both idx_1 and idx_1are there...

A reader, July 29, 2005 - 9:59 am UTC

Why can't oracle use idx_1 since that would be the fastest?

Tom Kyte
July 29, 2005 - 12:31 pm UTC

use the cbo....