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

ItemDescription
Gathering toolDBMS_STATS (ANALYZE is the old method and is not used for optimizer statistics)
Automatic gatheringThe auto optimizer stats collection job in the maintenance window. Gathers objects that have no statistics or are stale
Staleness thresholdChanged rows since the last gather reach STALE_PERCENT (default 10%)
Sample sizeESTIMATE_PERCENT defaults to AUTO_SAMPLE_SIZE. Reads everything, but computes NDV with an approximation algorithm
HistogramsMETHOD_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 invalidationNO_INVALIDATE defaults to AUTO_INVALIDATE. New statistics do not change the plan immediately; cursors are re-parsed after a delay
HistoryKeeps previous statistics for 31 days. Restore them with DBMS_STATS.RESTORE_TABLE_STATS
Dynamic samplingOPTIMIZER_DYNAMIC_SAMPLING defaults to 2: samples a table with no statistics just before execution
SandboxGathered 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

ValueView columnWhere it is used
Row countNUM_ROWSStarting point of every cardinality estimate
Block countBLOCKSCost of a full read (TABLE ACCESS FULL)
Average row lengthAVG_ROW_LENMemory estimates for hash joins and sorts

Column statistics

ValueView columnWhere it is used
Number of distinct valuesNUM_DISTINCT (NDV)Selectivity 1 / NDV of an equality condition, join cardinality
NULL countNUM_NULLSIS NULL conditions, rows dropped from a join
Minimum and maximum valuesLOW_VALUE, HIGH_VALUESelectivity of range conditions
DensityDENSITY1 / NDV when there is no histogram
HistogramHISTOGRAM, *_TAB_HISTOGRAMSPer-value selectivity. Skewed values

Index statistics

ValueView columnWhere it is used
HeightBLEVEL (number of levels from root to above the leaf)Cost of one descent of the index
Leaf block countLEAF_BLOCKSCost of a range scan
Number of key valuesDISTINCT_KEYSNDV of all columns of a composite index
Clustering factorCLUSTERING_FACTORNumber 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');
ColumnNUM_DISTINCTDENSITYHISTOGRAM
CUSTOMERS.GRADE30.333NONE
CUSTOMERS.REGION50.2NONE
ORDERS.STATUS30.333NONE
ORDERS.CUST_ID100,8240.0000099NONE

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.

IndexBLEVELLEAF_BLOCKSCLUSTERING_FACTORTable blocks / rows
ORDERS_PK (ORD_ID)24,31513,94014,099 / 2,000,000
ORDERS_X2 (STATUS, ORD_DT, ORD_ID)27,98748,771
ORDERS_X1 (CUST_ID, ORD_DT)26,8031,998,596
CUSTOMERS_X1 (GRADE)12491,722592 / 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.

ConditionEstimate without a histogramWhen it is wrong
col = valueNUM_ROWS × (1 / NDV)Values are skewed. Example: GRADE = 'VIP' → 100,000 ÷ 3 = 33,333 (actual 1,000)
col > valueNUM_ROWS × (HIGH − value) / (HIGH − LOW)Values are not evenly spread
f(col) = valueDefault selectivity 1% (= ), 5% (range)The column is transformed. Statistics cannot be used
cond1 AND cond2Product of the selectivities (assumes columns are independent)The columns are correlated
cond1 OR cond2s1 + s2 − s1 × s2Same
Equality join a.x = b.yrows 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.

ScenarioEstimateActualCause
28 Orders of high-volume customers1 per customer543 per customerSkew in the join key (CUST_ID). Average rows per key
29 VIP customers33,333 customers1,000 customersNo histogram
32 Index that skips the sort20 rows after passing 1,9361,938,506 rowsCorrelation 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.

TypeCondition to createMeaning
FrequencyNDV ≤ bucket count (254 by default)Exact row count per value
Top-FrequencyA few top values account for almost everythingTop values are exact, the rest are uniform
HybridNDV is greater than the bucket countAlso stores how many times each bucket's end value repeats
Height-BalancedNDV is greater than the bucket count and ESTIMATE_PERCENT is set explicitlyThe 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);
FeatureMethodWhen to use
Check staleness*_TAB_STATISTICS.STALE_STATS, or *_TAB_MODIFICATIONS after DBMS_STATS.FLUSH_DATABASE_MONITORING_INFOAfter a bulk load
Pending statisticsGather with the table preference PUBLISH = FALSE, test in a session with OPTIMIZER_USE_PENDING_STATISTICS = TRUE, and apply with PUBLISH_PENDING_STATSWhen new statistics might ruin plans
TransferCREATE_STAT_TABLE, EXPORT_TABLE_STATS, IMPORT_TABLE_STATSReproduce production statistics exactly in a development or validation DB
Set directlySET_TABLE_STATS, SET_COLUMN_STATSA 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

FeatureBehaviorTrace in the execution plan
Dynamic samplingAt 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 feedbackIf A-Rows differs greatly from E-Rows after execution, the next parse uses the actual valuesNote: statistics feedback used
Adaptive planCounts rows during execution and chooses between NL and hash joinNote: 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

ItemOraclePostgreSQLSQL Server
GatheringDBMS_STATSANALYZE (autovacuum runs it automatically)UPDATE STATISTICS (automatic update)
HistogramsOnly on skewed columns used in conditions (SIZE AUTO)MCV + histogram on every column (default_statistics_target 100)Up to 200 steps per statistics object
CorrelationColumn group statisticsCREATE STATISTICS … (dependencies, ndistinct, mcv)Multi-column statistics (density of the leading column)
ClusteringCLUSTERING_FACTORpg_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.

Related pages