05.11.2015 Views

Apress.Expert.Oracle.Database.Architecture.9i.and.10g.Programming.Techniques.and.Solutions.Sep.2005

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

CHAPTER 11 ■ INDEXES 481<br />

ops$tkyte@ORA10GR1> set autotrace on explain<br />

ops$tkyte@ORA10GR1> select count(y) from t where x < 50;<br />

COUNT(Y)<br />

----------<br />

49<br />

Execution Plan<br />

----------------------------------------------------------<br />

0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=3 Card=1 Bytes=28)<br />

1 0 SORT (AGGREGATE)<br />

2 1 TABLE ACCESS (BY INDEX ROWID) OF 'T' (TABLE) (Cost=3 Card=41 Bytes=1148)<br />

3 2 INDEX (RANGE SCAN) OF 'SYS_C009167' (INDEX (UNIQUE)) (Cost=2 Card=41)<br />

it will happily use the index; however, we’ll find that when the estimated number of rows to be<br />

retrieved via the index crosses a threshold (which varies depending on various optimizer settings,<br />

physical statistics, <strong>and</strong> so on), we’ll start to observe a full table scan:<br />

ops$tkyte@ORA10GR1> select count(y) from t where x < 15000;<br />

COUNT(Y)<br />

----------<br />

14999<br />

Execution Plan<br />

----------------------------------------------------------<br />

0 SELECT STATEMENT Optimizer=ALL_ROWS (Cost=57 Card=1 Bytes=28)<br />

1 0 SORT (AGGREGATE)<br />

2 1 TABLE ACCESS (FULL) OF 'T' (TABLE) (Cost=57 Card=14994 Bytes=419832)<br />

This example shows the optimizer won’t always use an index <strong>and</strong>, in fact, it makes the<br />

right choice in skipping indexes. While tuning your queries, if you discover that an index isn’t<br />

used when you think it “ought to be,” don’t just force it to be used—test <strong>and</strong> prove first that the<br />

index is indeed faster (via elapsed <strong>and</strong> I/O counts) before overruling the CBO. Reason it out.<br />

Case 6<br />

We haven’t analyzed our tables in a while. They used to be small, but now when we look at<br />

them, they have grown quite large. An index will now make sense, whereas it didn’t originally.<br />

If we analyze the table, it will use the index.<br />

Without correct statistics, the CBO cannot make the correct decisions.<br />

Index Case Summary<br />

In my experience, these six cases are the main reasons I find that indexes are not being used.<br />

It usually boils down to a case of “They cannot be used—using them would return incorrect<br />

results” or “They should not be used—if they were used, performance would be terrible.”

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!