Sub topic 3
Selectivity and statistics: why the optimizer may skip an index
This chapter assumes you can run EXPLAIN PLAN and read a basic plan, and that you know how a B-tree index is searched. You do not need to know how the optimizer's cost model is built. You only need the working model below.
A predicate can be written perfectly for an index and Oracle may still choose a full table scan. This is often correct. It is also sometimes caused by bad statistics. This chapter shows you how to tell the two cases apart.
Selectivity and cardinality
Selectivity is the fraction of rows a predicate keeps. It is a number between 0 and 1. Cardinality is the estimated number of rows a plan step returns.
For an equality predicate on a column with no histogram, the optimizer estimates:
- selectivity = 1 / number of distinct values (NDV)
- cardinality = selectivity × number of rows in the table
A table of 1,000,000 orders with 500,000 distinct customer_id values gives a selectivity of 0.000002 for customer_id = 42. The estimated cardinality is 2 rows. That is a good case for an index.
A column with 3 distinct values, such as status, gives a selectivity of about 0.33. The estimate is about 333,000 rows. That is a poor case for an index.
Why a low-selectivity index loses
An index range scan finds row addresses (ROWIDs) in the index. Then Oracle reads the table block for each ROWID. These reads are mostly single-block reads at scattered locations.
A full table scan reads the table's blocks in large sequential multiblock reads. It reads each block once.
If the predicate keeps a large share of the rows, the index path can read the same table block many times and make far more I/O calls than a scan. The optimizer compares the estimated costs and picks the lower one. There is no fixed percentage threshold. The break-even point depends on:
- how many rows qualify
- the table size in blocks
- the clustering factor of the index
- the multiblock read count the optimizer assumes
The clustering factor measures how well the table's physical row order matches the index order. It is stored in USER_INDEXES.CLUSTERING_FACTOR. A value near the number of table blocks means rows with neighboring keys sit in the same blocks, so an index range scan revisits few blocks. A value near the number of rows means neighboring keys are scattered, so each ROWID likely needs its own block read.
SELECT index_name, clustering_factor, num_rows, leaf_blocks
FROM user_indexes
WHERE table_name = 'ORDERS';
SELECT table_name, num_rows, blocks
FROM user_tables
WHERE table_name = 'ORDERS';Compare clustering_factor with blocks and with num_rows in the two results. The closer it is to blocks, the cheaper the index range scan.
Optimizer statistics
The optimizer does not look at your data when it plans. It reads statistics stored in the data dictionary. Table statistics include the row count and block count. Column statistics include the number of distinct values, the lowest and highest values, the NULL count, and optionally a histogram. Index statistics include the number of leaf blocks, the tree height, and the clustering factor.
Gather them with DBMS_STATS, not with the old ANALYZE statement.
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(
ownname => USER,
tabname => 'ORDERS',
cascade => TRUE
);
END;
/cascade => TRUE gathers statistics on the table's indexes in the same call. Oracle also runs an automatic statistics job in a nightly maintenance window, so most tables already have statistics. Problems show up when the data changes sharply between runs, for example after a bulk load.
Check how current the statistics are:
SELECT table_name, num_rows, last_analyzed, stale_stats
FROM user_tab_statistics
WHERE table_name = 'ORDERS';STALE_STATS = 'YES' means more than about 10 percent of the rows have changed since the last gathering.
Histograms and skewed data
Without a histogram, the optimizer assumes all values of a column are equally common. If 98 percent of status values are 'SHIPPED' and 0.1 percent are 'FAILED', the uniform estimate is wrong for both.
A histogram records how the values are distributed. With one, the optimizer estimates status = 'FAILED' as a few rows and chooses an index. It estimates status = 'SHIPPED' as nearly the whole table and chooses a full scan.
BEGIN
DBMS_STATS.GATHER_TABLE_STATS(
ownname => USER,
tabname => 'ORDERS',
method_opt => 'FOR COLUMNS status SIZE AUTO'
);
END;
/SIZE AUTO lets Oracle decide whether a histogram is worth building. It looks at the column's data distribution and at which columns have appeared in predicates. Do not add histograms to every column. They cost time to gather and can make plans less stable.
Seeing a bad estimate in a plan
A plan shows the estimated row count in the Rows column. To compare it with reality, run the statement and show the actual counts.
SELECT /*+ GATHER_PLAN_STATISTICS */ order_id
FROM orders
WHERE status = 'FAILED';
SELECT *
FROM TABLE(DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'));In the output, E-Rows is the estimate and A-Rows is the actual number. A large gap between them, such as an estimate of 10 and an actual of 400,000, points to a statistics problem. Fix the estimate first. Do not force the plan with a hint.
Common causes of skipped indexes
| Symptom | Likely cause | What to check |
|---|---|---|
| Full scan on a column with few distinct values | Low selectivity, so the scan is cheaper | `NUM_DISTINCT` in `USER_TAB_COL_STATISTICS` |
| Full scan, `E-Rows` far below `A-Rows` | Stale statistics | `STALE_STATS`, `LAST_ANALYZED` |
| Index used for rare values, ignored for common ones | Skewed data, correct choice | Histogram on the column |
| Full scan on a small table | A few blocks read in one call beat an index lookup | `BLOCKS` in `USER_TABLES` |
| Index scan on rare values that is still slow | Poor clustering factor | `CLUSTERING_FACTOR` |
Do not force the index first
You can add an INDEX hint to make Oracle use an index. This is a poor first move. If the full scan really is cheaper, the hint makes the query slower. If the cause is a bad estimate, the hint hides the problem, and other queries on the same table keep suffering from it.
A better order of work:
- Compare
E-RowswithA-Rows. - If they differ, regather statistics, and add a histogram if the data is skewed.
- If they match and the index is still not used, the optimizer likely has the cheaper plan. Consider whether the query should return that many rows at all.
- Use a hint only to test a hypothesis, not as the permanent fix.
Exercise
A query WHERE status = 'SHIPPED' on a 2,000,000-row table does a full table scan, although status is indexed. About 97 percent of the rows have that status. A colleague wants to add an INDEX hint. What do you check, and what do you tell them?
Show answer
Check E-Rows against A-Rows with GATHER_PLAN_STATISTICS and DBMS_XPLAN.DISPLAY_CURSOR(format => 'ALLSTATS LAST'). If the estimate is close to 1,940,000 rows, the optimizer is right: reading almost the whole table through an index means many single-block reads and is slower than a multiblock full scan. The hint would make the query slower. If the estimate is far too low, the statistics are the problem, so regather them and consider a histogram on status. The hint is not the fix in either case.
Exercise
Two indexes on the same table both have a selective predicate that keeps 1 percent of the rows. One index has a clustering factor close to the table's block count and the other has a clustering factor close to its row count. Which is cheaper to range scan, and why?
Show answer
The index with the clustering factor close to the block count. Rows with neighboring keys sit in the same table blocks, so the scan visits few distinct blocks. With a clustering factor near the row count, neighboring keys are spread over many blocks, so nearly every ROWID costs its own block read.