Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL/Oracle: when indexes on multiple columns can be used

Tags:

If I create an index on columns (A, B, C), in that order, my understanding is that the database will be able to use it even if I search only on (A), or (A and B), or (A and B and C), but not if I search only on (B), or (C), or (B and C). Is this correct?

like image 991
avernet Avatar asked Sep 11 '08 23:09

avernet


People also ask

Is indexes allowed in multiple columns?

A composite index is an index on multiple columns. MySQL allows you to create a composite index that consists of up to 16 columns. A composite index is also known as a multiple-column index.

What will happen if you apply index on multiple-column?

An index with more than one column aggregates the contents.

How do indexes on multiple columns work?

A multicolumn GiST index can be used with query conditions that involve any subset of the index's columns. Conditions on additional columns restrict the entries returned by the index, but the condition on the first column is the most important one for determining how much of the index needs to be scanned.

Can we create index on multiple columns in SQL?

Multicolumn indexes can: be created on up to 32 columns. be used for partial indexing.


2 Answers

There are actually three index-based access methods that Oracle can use when a predicate is placed on a non-leading column of an index.

i) Index skip-scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#PFGRF10105

ii) Fast full index scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i52044

iii) Index full scan: http://download.oracle.com/docs/cd/B19306_01/server.102/b14211/optimops.htm#i82107

I've most often seen the fast full index scan "in the wild", but all are possible.

like image 68
David Aldridge Avatar answered Oct 24 '22 01:10

David Aldridge


That is not correct. Always best to come up with a test case that represents your data and see for yourself. If you want to really understand the Oracle SQL Optimizer google Jonathan Lewis, read his books, read his blog, check out his website, the guy is amazing, and he always generates test cases.

create table mytab nologging as (
select mod(rownum, 3) x, rownum  y, mod(rownum, 3) z from all_objects, (select 'x' from user_tables where rownum < 4)
);

create index i on mytab (x, y, z);

exec dbms_stats.gather_table_stats(ownname=>'DBADMIN',tabname=>'MYTAB', cascade=>true);

set autot trace exp

select * from mytab where y=5000;

Execution Plan
----------------------------------------------------------
   0      SELECT STATEMENT Optimizer=CHOOSE (Cost=1 Card=1 Bytes=10)
   1    0   INDEX (SKIP SCAN) OF 'I' (INDEX) (Cost=1 Card=1 Bytes=10)
like image 38
Ethan Post Avatar answered Oct 24 '22 00:10

Ethan Post