Oracle Optimizer Statistics
Optimizer statistics summarize the size and distribution of data. They include a table's row count and block count, a column's number of distinct values (NDV) and NULL count, the distribution of values (histograms), and an index's height and clustering factor. Without executing the statement, the optimizer estimates the row count (cardinality) of each step from these values alone, and from those row counts it chooses the access path, join order, and join method. When the E-Rows of an execution plan differ greatly from A-Rows, it is usually because the statistics did not summarize the data well, or because the optimizer's estimation rules (columns are independent, values are evenly spread) do not match the data.
Summary
| Item | Description |
|---|---|
| Gathering tool | DBMS_STATS (ANALYZE is the old method and is not used for optimizer statistics) |
| Automatic gathering | The auto optimizer stats collection job in the maintenance window. Gathers objects that have no statistics or are stale |
| Staleness threshold | Changed rows since the last gather reach STALE_PERCENT (default 10%) |
| Sample size | ESTIMATE_PERCENT defaults to AUTO_SAMPLE_SIZE. Reads everything, but computes NDV with an approximation algorithm |
| Histograms | METHOD_OPT defaults to FOR ALL COLUMNS SIZE AUTO. Created only for columns that have been used in conditions (COL_USAGE$) and have skewed values |
| Cursor invalidation | NO_INVALIDATE defaults to AUTO_INVALIDATE. New statistics do not change the plan immediately; cursors are re-parsed after a delay |
| History | Keeps previous statistics for 31 days. Restore them with DBMS_STATS.RESTORE_TABLE_STATS |
| Dynamic sampling | OPTIMIZER_DYNAMIC_SAMPLING defaults to 2: samples a table with no statistics just before execution |
| Sandbox | Gathered once right after loading, then locked with LOCK_SCHEMA_STATS. The histogram of every column is NONE |
The defaults above were checked in the sandbox (Oracle 23ai) with DBMS_STATS.GET_PREFS and V$PARAMETER.
Kinds of Statistics
Table statistics
| Value | View column | Where it is used |
|---|---|---|
| Row count | NUM_ROWS | Starting point of every cardinality estimate |
| Block count | BLOCKS | Cost of a full read (TABLE ACCESS FULL) |
| Average row length | AVG_ROW_LEN | Memory estimates for hash joins and sorts |
Column statistics
| Value | View column | Where it is used |
|---|---|---|
| Number of distinct values | NUM_DISTINCT (NDV) | Selectivity 1 / NDV of an equality condition, join cardinality |
| NULL count | NUM_NULLS | IS NULL conditions, rows dropped from a join |
| Minimum and maximum values | LOW_VALUE, HIGH_VALUE | Selectivity of range conditions |
| Density | DENSITY | 1 / NDV when there is no histogram |
| Histogram | HISTOGRAM, *_TAB_HISTOGRAMS | Per-value selectivity. Skewed values |
Index statistics
| Value | View column | Where it is used |
|---|---|---|
| Height | BLEVEL (number of levels from root to above the leaf) | Cost of one descent of the index |
| Leaf block count | LEAF_BLOCKS | Cost of a range scan |
| Number of key values | DISTINCT_KEYS | NDV of all columns of a composite index |
| Clustering factor | CLUSTERING_FACTOR | Number of block changes when reading the table in index order. Determines the cost of reading the table through the index |
Actual Sandbox Values
SELECT table_name, column_name, num_distinct, density, num_nulls, histogram
FROM all_tab_col_statistics
WHERE owner = 'TUNE' AND table_name IN ('ORDERS', 'CUSTOMERS');
SELECT index_name, blevel, leaf_blocks, distinct_keys, clustering_factor, num_rows
FROM all_indexes
WHERE owner = 'TUNE' AND table_name IN ('ORDERS', 'CUSTOMERS');
| Column | NUM_DISTINCT | DENSITY | HISTOGRAM |
|---|---|---|---|
CUSTOMERS.GRADE | 3 | 0.333 | NONE |
CUSTOMERS.REGION | 5 | 0.2 | NONE |
ORDERS.STATUS | 3 | 0.333 | NONE |
ORDERS.CUST_ID | 100,824 | 0.0000099 | NONE |
The actual distribution is VIP 1%, GOLD 9%, NORMAL 90% for GRADE and DONE 90%, PAID 7%, CANCELED 3% for STATUS, but with no histogram the optimizer treats each value as one third. The NDV of ORDERS.CUST_ID, 100,824, is slightly larger than the actual customer count of 100,000, because NDV is computed with an approximation algorithm.
| Index | BLEVEL | LEAF_BLOCKS | CLUSTERING_FACTOR | Table blocks / rows |
|---|---|---|---|---|
ORDERS_PK (ORD_ID) | 2 | 4,315 | 13,940 | 14,099 / 2,000,000 |
ORDERS_X2 (STATUS, ORD_DT, ORD_ID) | 2 | 7,987 | 48,771 | |
ORDERS_X1 (CUST_ID, ORD_DT) | 2 | 6,803 | 1,998,596 | |
CUSTOMERS_X1 (GRADE) | 1 | 249 | 1,722 | 592 / 100,000 |
The clustering factor lies between the block count (best) and the row count (worst). Orders were entered in ORD_ID order, so ORDERS_PK is almost equal to the block count, and customer numbers have no relation to order sequence, so ORDERS_X1 is almost equal to the row count. Reading the same 1,000 rows touches a few blocks in ORDERS_PK order but close to 1,000 blocks in ORDERS_X1 order (Scenario 14).
Cardinality Estimation
The optimizer calculates row counts with the rules below. When a rule's assumption does not match the data, E-Rows is wrong.
| Condition | Estimate without a histogram | When it is wrong |
|---|---|---|
col = value | NUM_ROWS × (1 / NDV) | Values are skewed. Example: GRADE = 'VIP' → 100,000 ÷ 3 = 33,333 (actual 1,000) |
col > value | NUM_ROWS × (HIGH − value) / (HIGH − LOW) | Values are not evenly spread |
f(col) = value | Default selectivity 1% (= ), 5% (range) | The column is transformed. Statistics cannot be used |
cond1 AND cond2 | Product of the selectivities (assumes columns are independent) | The columns are correlated |
cond1 OR cond2 | s1 + s2 − s1 × s2 | Same |
Equality join a.x = b.y | rows of A × rows of B ÷ max(NDV(a.x), NDV(b.y)) | The join key values are skewed. Rows per key are treated as an average |
Every estimation error seen in the scenarios comes from these rules.
| Scenario | Estimate | Actual | Cause |
|---|---|---|---|
| 28 Orders of high-volume customers | 1 per customer | 543 per customer | Skew in the join key (CUST_ID). Average rows per key |
| 29 VIP customers | 33,333 customers | 1,000 customers | No histogram |
| 32 Index that skips the sort | 20 rows after passing 1,936 | 1,938,506 rows | Correlation between ORD_ID and ORD_DT. Assumes matching rows are spread evenly |
Histograms
A histogram holds the distribution of values in buckets and gives a different selectivity per value. Since 12c, the types are as follows.
| Type | Condition to create | Meaning |
|---|---|---|
| Frequency | NDV ≤ bucket count (254 by default) | Exact row count per value |
| Top-Frequency | A few top values account for almost everything | Top values are exact, the rest are uniform |
| Hybrid | NDV is greater than the bucket count | Also stores how many times each bucket's end value repeats |
| Height-Balanced | NDV is greater than the bucket count and ESTIMATE_PERCENT is set explicitly | The method up to 11g. When gathered with AUTO_SAMPLE_SIZE, Hybrid replaces it from 12c |
SIZE AUTO creates histograms only for columns that have been used in conditions. When the optimizer parses a statement, it records the columns used in conditions in SYS.COL_USAGE$, and statistics gathering reads this record. The sandbox gathered statistics right after loading, before any statement ran, so no columns had been used and every histogram is NONE. COL_USAGE$ now holds 44 records for the TUNE schema, but the statistics are locked, so they are not gathered again.
NOTE With a histogram, the best plan depends on the bind variable value. Oracle peeks at the bind value on first execution (Bind Peeking) and splits the cursor into several if performance varies greatly with the value (Adaptive Cursor Sharing). Without a histogram, every value gets the same estimate.
Correlation between columns: extended statistics
The rule of multiplying the selectivities of an AND condition is badly wrong when the columns are correlated (for example, province and city). A column group statistic counts the NDV of the two columns as if they were one.
SELECT DBMS_STATS.CREATE_EXTENDED_STATS('TUNE', 'CUSTOMERS', '(GRADE, REGION)') FROM dual;
EXEC DBMS_STATS.GATHER_TABLE_STATS('TUNE', 'CUSTOMERS', method_opt => 'FOR COLUMNS (GRADE, REGION) SIZE AUTO');
Statistics on an expression ('(UPPER(CUST_NM))') are created the same way. A correlation that is not between conditions, such as the one between a sort key and a condition column (Scenario 32), cannot be fixed with extended statistics.
Gathering, Locking, and Restoring
-- One table (including index statistics)
EXEC DBMS_STATS.GATHER_TABLE_STATS('TUNE', 'ORDERS');
-- Gather without histograms (the sandbox's practical case-study schema)
EXEC DBMS_STATS.GATHER_TABLE_STATS('TUNE', 'STK_ORD', method_opt => 'FOR ALL COLUMNS SIZE 1');
-- Histogram on a specific column only
EXEC DBMS_STATS.GATHER_TABLE_STATS('TUNE', 'CUSTOMERS', method_opt => 'FOR COLUMNS GRADE SIZE 254');
-- Change the per-table default
EXEC DBMS_STATS.SET_TABLE_PREFS('TUNE', 'ORDERS', 'STALE_PERCENT', '5');
-- Lock / unlock: automatic gathering skips locked statistics
EXEC DBMS_STATS.LOCK_TABLE_STATS('TUNE', 'ORDERS');
EXEC DBMS_STATS.UNLOCK_TABLE_STATS('TUNE', 'ORDERS');
-- Restore to yesterday's point in time
EXEC DBMS_STATS.RESTORE_TABLE_STATS('TUNE', 'ORDERS', SYSTIMESTAMP - INTERVAL '1' DAY);
| Feature | Method | When to use |
|---|---|---|
| Check staleness | *_TAB_STATISTICS.STALE_STATS, or *_TAB_MODIFICATIONS after DBMS_STATS.FLUSH_DATABASE_MONITORING_INFO | After a bulk load |
| Pending statistics | Gather with the table preference PUBLISH = FALSE, test in a session with OPTIMIZER_USE_PENDING_STATISTICS = TRUE, and apply with PUBLISH_PENDING_STATS | When new statistics might ruin plans |
| Transfer | CREATE_STAT_TABLE, EXPORT_TABLE_STATS, IMPORT_TABLE_STATS | Reproduce production statistics exactly in a development or validation DB |
| Set directly | SET_TABLE_STATS, SET_COLUMN_STATS | A table that has no data yet, experiments |
The sandbox locks statistics with LOCK_SCHEMA_STATS('TUNE') so that the same plan appears no matter who runs a statement or when. The sandbox execution account cannot call DBMS_STATS.
When Statistics Are Missing or Insufficient
| Feature | Behavior | Trace in the execution plan |
|---|---|---|
| Dynamic sampling | At parse time, reads some blocks of a table with no statistics to estimate. Level 2 is the default. Hint DYNAMIC_SAMPLING(t 4) | Note: dynamic statistics used |
| Statistics feedback | If A-Rows differs greatly from E-Rows after execution, the next parse uses the actual values | Note: statistics feedback used |
| Adaptive plan | Counts rows during execution and chooses between NL and hash join | Note: this is an adaptive plan, STATISTICS COLLECTOR |
An adaptive plan counts only the row count of the driving set. It cannot correct the case where the driving row count is right but the inner row count is wrong (the skewed join key in Scenario 28).
Comparison with Other DBMSs
| Item | Oracle | PostgreSQL | SQL Server |
|---|---|---|---|
| Gathering | DBMS_STATS | ANALYZE (autovacuum runs it automatically) | UPDATE STATISTICS (automatic update) |
| Histograms | Only on skewed columns used in conditions (SIZE AUTO) | MCV + histogram on every column (default_statistics_target 100) | Up to 200 steps per statistics object |
| Correlation | Column group statistics | CREATE STATISTICS … (dependencies, ndistinct, mcv) | Multi-column statistics (density of the leading column) |
| Clustering | CLUSTERING_FACTOR | pg_stats.correlation | (the clustered index is the table order) |
The sandbox's PostgreSQL has the MCV of the grade, so it estimates VIP at 970 customers. This is why only Oracle chooses a hash join for the same statement (the PostgreSQL version of Scenario 29).
NOTE Defaults (
STALE_PERCENT, the histogram bucket count, the dynamic sampling level) and the automatic gathering method can differ by version. The values in this document were checked on the sandbox's Oracle 23ai.