With Oracle 9i, the Cost-Based Optimizer (CBO) is equipped with many useful features, one of them is “Index skip scan“. In previous releases a composite index could only be used if the first column, the leading edge, of the index was referenced in the WHERE clause of a statement. In Oracle 9i this restriction is removed because the optimizer can perform skip scans to retrieve rowids for values that do not use the prefix. This means even if you have a composite index on more than one column and you use the non-prefix column alone in your SQL, it may still use index. (Earlier I use to think that it will not use index :))
Its not always guaranteed that the Index Skip Scan will be used, this is because Cost-Based Optimizer (CBO) will calculate the cost of using the index and if it is more than that of full table scan, then it may not use index.
This approach is advantageous because:
It reduces the number of indexes needed to support a range of queries. This increases performance by reducing index maintenance and decreases wasted space associated with multiple indexes.
The prefix column should be the most discriminating and the most widely used in queries. These two conditions do not always go hand in hand which makes the decision difficult. In these situations skip scanning reduces the impact of making the “wrong” decision.
Index skip scan works differently from a normal index (range) scan. A normal range scan works from top to bottom first and then move horizontal. But a Skip scan includes several range scans in it. Since the query lacks the leading column it will rewrite the query into smaller queries and each doing a range scan.
Consider following example where we create a test table and create index on first two columns a and b. Also we put some dummy data inside test table. See how Index is getting selected when we execute select statement with column b in where clause.
CREATETABLEtest (a NUMBER, b NUMBER, c NUMBER);
ONtest (a, b);
BEGINFOR i IN1 .. 100000LOOPINSERTINTOtestVALUES (MOD (i, 5), i, 100);
I above example, "select * from test where b=95267" was broken down to several small range scan queries. It was effectively equivalent to following:
FROMtestWHERE a = 0AND b = 95267UNIONSELECT *
FROMtestWHERE a = 1AND b = 95267UNIONSELECT *
FROMtestWHERE a = 2AND b = 95267UNIONSELECT *
FROMtestWHERE a = 3AND b = 95267UNIONSELECT *
FROMtestWHERE a = 4AND b = 95267;
In concrete, saying that skip scan is not as efficient as normal “single range scan” is correct. But yet saves some disk space and overhead of maintaining another index.